Building a Backend API with File Conversion and Upload
To build a backend API that handles file conversion and upload, here's a comprehensive approach:
System Architecture
- Backend API (Node.js/Express, Python/Flask/Django, or other framework)
- File Conversion Service
- File Storage (local or cloud storage like AWS S3)
Implementation Steps
1. Set Up Your Backend API
For a Node.js example:
javascript
// server.js
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { exec } = require('child_process');
const app = express();
const upload = multer({ dest: 'uploads/' });
// File conversion endpoint
app.post('/convert', upload.single('file'), (req, res) => {
if (!req.file) {
return res.status(400).send('No file uploaded');
}
const { originalname, path: filePath, mimetype } = req.file;
const { targetFormat } = req.body;
// Validate input
if (!targetFormat) {
return res.status(400).send('Target format is required');
}
// Convert file (example using ffmpeg for media files)
const outputPath = `converted/${originalname.split('.')[0]}.${targetFormat}`;
exec(`ffmpeg -i ${filePath} ${outputPath}`, (error, stdout, stderr) => {
if (error) {
console.error(`Conversion error: ${error}`);
return res.status(500).send('Conversion failed');
}
// Return the converted file
res.download(outputPath, (err) => {
// Clean up
fs.unlinkSync(filePath);
fs.unlinkSync(outputPath);
});
});
});
// File upload endpoint
app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) {
return res.status(400).send('No file uploaded');
}
// Here you would typically save to permanent storage
res.json({
message: 'File uploaded successfully',
filename: req.file.originalname,
size: req.file.size
});
});
app.listen(3000, () => console.log('Server running on port 3000'));
2. Frontend Input Components
You'll need three main input components:
- Source File Selection:
html
<input type="file" id="sourceFile" name="file">
- Target Format Selection:
html
<select id="targetFormat">
<option value="pdf">PDF</option>
<option value="docx">DOCX</option>
<option value="jpg">JPG</option>
<option value="png">PNG</option>
<!-- Add more formats as needed -->
</select>
- Submit Button:
html
<button id="convertButton">Convert and Upload</button>
3. Frontend JavaScript to Handle Submission
javascript
document.getElementById('convertButton').addEventListener('click', async () => {
const fileInput = document.getElementById('sourceFile');
const formatSelect = document.getElementById('targetFormat');
if (fileInput.files.length === 0) {
alert('Please select a file');
return;
}
const formData = new FormData();
formData.append('file', fileInput.files[0]);
formData.append('targetFormat', formatSelect.value);
try {
const response = await fetch('http://localhost:3000/convert', {
method: 'POST',
body: formData
});
if (response.ok) {
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `converted.${formatSelect.value}`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
} else {
const error = await response.text();
alert(`Error: ${error}`);
}
} catch (err) {
console.error('Error:', err);
alert('An error occurred during conversion');
}
});
File Conversion Options
The conversion method depends on your file types:
-
For documents (PDF, DOCX, etc.):
- Use LibreOffice in headless mode
- Use specialized libraries like pdf-lib, docx, etc.
-
For images:
- Use ImageMagick or Sharp library
- Example with Sharp:
javascript
const sharp = require('sharp');
await sharp(inputPath).toFormat(targetFormat).toFile(outputPath);
-
For audio/video:
- Use FFmpeg as shown in the example
Deployment Considerations
-
Security:
- Validate all file uploads
- Set file size limits
- Use proper authentication
-
Scalability:
- Consider using a queue system (like RabbitMQ) for large files
- Implement rate limiting
-
Storage:
- For production, use cloud storage with proper access controls
Would you like me to elaborate on any specific part of this implementation?