DEV Community

Sabir Sheikh
Sabir Sheikh

Posted on

Upload File Using Fetch Method

Using the fetch method, you can send files from the frontend to your Node.js backend for processing. Here's a simple example:

1. Backend (Node.js with Express & Multer)
Set up an Express server to handle file uploads:

const express = require('express');
const multer = require('multer');
const cors = require('cors');

const app = express();
app.use(cors());

const storage = multer.diskStorage({
    destination: './uploads/',
    filename: (req, file, cb) => {
        cb(null, file.originalname);
    }
});

const upload = multer({ storage: storage });

app.post('/upload', upload.single('file'), (req, res) => {
    res.json({ message: 'File uploaded successfully', filename: req.file.filename });
});

app.listen(3000, () => console.log('Server running on port 3000'));
Enter fullscreen mode Exit fullscreen mode

2. Frontend (Using fetch to Upload File)
Use JavaScript's fetch API to send a file to your backend:

<input type="file" id="fileInput">
<button onclick="uploadFile()">Upload</button>

<script>
function uploadFile() {
    const fileInput = document.getElementById('fileInput');
    const file = fileInput.files[0];

    const formData = new FormData();
    formData.append('file', file);

    fetch('http://localhost:3000/upload', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
}
</script>

Enter fullscreen mode Exit fullscreen mode

3. Running the Project
Start the Node.js server (node server.js)

Open the HTML file in your browser, select a file, and click "Upload."

This will send the file to the backend using the fetch method and store it in the uploads directory.

Would you like to extend this to store blog content dynamically in a database?

Top comments (0)