# API Upload error

**URL:** <https://discuss.roboflow.com/t/api-upload-error/5616>\
**Category:** 🤝  Community Help\
**Tags:** bugs\
**Created:** [May 3, 2024, 7:52pm UTC](https://discuss.roboflow.com/t/api-upload-error/5616 "2024-05-03T19:52:25Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Youssef\_Dh](https://yyz1.discourse-cdn.com/flex029/user_avatar/discuss.roboflow.com/youssef_dh/32/4477_2.png) [@Youssef\_Dh](https://discuss.roboflow.com/u/Youssef_Dh)\
**Post date:** [May 3, 2024, 7:52pm UTC](https://discuss.roboflow.com/t/api-upload-error/5616/1 "2024-05-03T19:52:25Z")

</div>

Hello ,  
I have a plugin project that mainly records videos and sends them to database and i want to send those videos to roboflow as frames after extracting them with FFmpeg.  
when trying to send them i get a bad gateway error 502 in Devtools, im gonna leave my function code here :  
async function sendVideoToRoboflow(videoId) {  
try {  
// Fetch the video from the server  
const response = await fetch(`http://localhost:3000/video/${videoId}`);  
if (!response.ok) {  
console.error(‘Failed to fetch video:’, response.statusText);  
return;  
}

```
    // Convert the video blob to a Blob URL
    const videoBlob = await response.blob();

    // Extract frames from the video using FFmpeg
    const ffmpegResponse = await fetch(`http://localhost:3000/extractFrames/${videoId}`, {
        method: 'POST',
        body: videoBlob
    });
    if (!ffmpegResponse.ok) {
        console.error('Failed to extract frames:', ffmpegResponse.statusText);
        return;
    }

    // Assuming the response from FFmpeg contains the URLs of extracted frames
    const frameUrls = await ffmpegResponse.json();

    // Create a FormData object to send the data
    const formData = new FormData();
    frameUrls.forEach((frameUrl, index) => {
        formData.append('file' + index, frameUrl);
        formData.append('name' + index, `frame_${index}.png`);
        formData.append('split' + index, 'train');
    });

    // Send the FormData to Roboflow's API
    const roboflowResponse = await fetch('https://api.roboflow.com/dataset/XXX/upload', {
        method: 'POST',
        body: formData,
        headers: {
            'Authorization': 'Bearer (My API key is here but i removed it since its private)'
        }
    });

    if (roboflowResponse.ok) {
        console.log('Frames sent to Roboflow successfully!');
        console.log(roboflowResponse.body);
    } else {
        console.error('Failed to send frames to Roboflow:', roboflowResponse.statusText);
    }
} catch (error) {
    console.error('Error sending video to Roboflow:', error);
}

```

}  
and here’s the endpoint from my backend code:

// Endpoint to extract frames from a video by its ID  
app.post(‘/extractFrames/:videoId’, async (req, res) =\> {  
try {  
const videoId = req.params.videoId;

```
// Find the video in the database by its ID
const video = await Video.findById(videoId);
if (!video) {
  return res.status(404).send('Video not found');
}

// Create directories for temporary video and extracted frames
const tempVideoDir = path.join(__dirname, 'temp_videos');
const extractedFramesDir = path.join(__dirname, 'extracted_frames');

// Ensure directories exist, create if not
if (!fs.existsSync(tempVideoDir)) {
  fs.mkdirSync(tempVideoDir);
}
if (!fs.existsSync(extractedFramesDir)) {
  fs.mkdirSync(extractedFramesDir);
}

// Write the video data to a temporary file
const tempFilePath = path.join(tempVideoDir, `temp_${videoId}.webm`);
fs.writeFileSync(tempFilePath, video.data);

console.log('Starting frame extraction process with FFmpeg...');
// Use FFmpeg to extract frames from the video
ffmpeg(tempFilePath)
  .output(path.join(extractedFramesDir, 'frames_%03d.png')) // Output frame files
  .on('end', () => {
    console.log('Frame extraction process completed successfully.');
    // Read the extracted frame files and send their URLs back as response
    const frameUrls = [];
    const frameFiles = fs.readdirSync(extractedFramesDir);
    frameFiles.forEach(file => {
      if (file.startsWith('frames_')) {
        frameUrls.push(`http://localhost:3000/${path.join('extracted_frames', file)}`);
      }
    });

    console.log('Sending frame URLs back as response...');
    res.status(200).json(frameUrls);
  })
  .on('error', (err) => {
    console.error('Error extracting frames:', err);
    res.status(500).send('Error extracting frames');
  })
  .run();

```

} catch (error) {  
console.error(‘Error extracting frames:’, error);  
res.status(500).send(‘Error extracting frames’);  
}  
});

 ![teswiraRoboflow1](https://canada1.discourse-cdn.com/flex029/uploads/roboflow1/original/2X/3/37dae53746390fc173b15d7c46f28d8f2a01fc74.png)

- **Project Type: Object Detection**
- **Windows 10 | OperaGX**
- **Support Key: Cvo4D3NXT1ZOf5F9FdnVugp280Z2**

---

<div class="post-metadata">

**Author:** ![system](https://canada1.discourse-cdn.com/flex029/uploads/roboflow1/original/1X/bb6edbfa56d0cf2ee603f061e9e09103502cc8cc.png) [@system](https://discuss.roboflow.com/u/system)\
**Post date:** [May 24, 2024, 7:53pm UTC](https://discuss.roboflow.com/t/api-upload-error/5616/2 "2024-05-24T19:53:21Z")

</div>

Closed on May 24, 2024, 7:53pm UTC

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.
