Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cant get multipart/form-data in express js

I'm trynna get the form`s data that contains a file, and I use Multer for handling that, but for some reason, my req.body is returning {}, but when I use the normal form without multipart data, it gives me all the data, so the problem is with Multer, here's my code

 const express = require("express");
const app = express();
const multer = require("multer");
app.listen(8000);
let upload = multer({ dest: "uploads/" });
upload.single("logo");
app.use(express.urlencoded({ extended: true }));

app.post("/", (req, res) => {
  console.log(req.file);
});
like image 574
Farid Ghaderi Avatar asked Oct 20 '25 14:10

Farid Ghaderi


2 Answers

const express = require("express");
const app = express();
const multer = require("multer");
app.listen(8000);
let upload = multer({ dest: "uploads/" });
app.use(express.urlencoded({ extended: true }));

app.post("/", upload.single("logo"), (req, res) => {
  console.log(req.file);
});

You need to specify upload.single as middleware.

like image 115
kunwar97 Avatar answered Oct 23 '25 04:10

kunwar97


This is working code in my project.

const path = require("path");
const multer = require('multer');

const fileStorage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'images');
    },
    filename: (req, file, cb) => {
        cb(null, new Date().toISOString()+ "-" + file.originalname);
    }
});

const fileFilter = (req, file, cb) => {
    if (
        file.mimetype === 'image/png' ||
        file.mimetype === 'image/jpg' ||
        file.mimetype === 'image/jpeg'
    ) {
        cb(null, true);
    } else {
        cb(null, false);
    }
};

app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(multer({ storage: fileStorage, fileFilter: fileFilter }).single('image'));
app.use(express.static(path.join(__dirname, 'public')));
app.use("/images", express.static(path.join(__dirname, 'images')));

app.post("/", (req, res) => {
  console.log(req.file);
});

app.listen(5000, () => console.log("Server Started!"));

like image 30
yakohere Avatar answered Oct 23 '25 03:10

yakohere



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!