Privacy · Terms of use · Contact ·

About · AskSFer © 2024

Node.js: How to Handle File Uploads with Express?

Time

asked 235 days ago

Answers

0Answers

Views

13Views

Hi everyone! I'm currently working on a Node.js project using Express and I'm looking for guidance on handling file uploads. I need to implement a feature where users can upload files (images, documents, etc.) to my server. Could someone please provide insights, best practices, or a code example on how to handle file uploads using Express in Node.js? Any help would be greatly appreciated. Thank you!

// app.js (or your main server file)

const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();

// Enable file upload middleware
app.use(fileUpload());

// File upload endpoint
app.post('/upload', (req, res) => {
  if (!req.files || Object.keys(req.files).length === 0) {
    return res.status(400).send('No files were uploaded.');
  }

  // The name of the input field (e.g. "file") is used to retrieve the uploaded file
  const uploadedFile = req.files.file;

  // Move the file to a specified location on the server
  uploadedFile.mv(`./uploads/${uploadedFile.name}`, (err) => {
    if (err) {
      return res.status(500).send(err);
    }

    res.send('File uploaded!');
  });
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
Not result illustration

There is no answer yet!

Be the first to break the silence! Answer the question and kickstart the discussion. our query could be the next big thing others learn from. Get involved!

Top Questions