cant get multipart/form-data in express js - node.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);
});

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.

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!"));

Related

Multer nodejs - req.file is undefined

I am creating an app using Node, Express and ejs and multer for uploading images. Every time I submit the form, req.file is undefined. I've spent the entire day troubleshooting but can't figure out what I'm doing wrong.
HTML
<form action="/post" id="formPost" method="post" enctype="multipart/form-data">
<input class="img-file" type="file" name="image" required>
<input class="submit" type="submit" value="Post" />
</form>
app.js
const path = require('path');
const express = require('express');
const morgan = require('morgan');
const bodyParser = require("body-parser");
const multer = require('multer');
const app = express();
app.use(express.static(path.join(__dirname, 'public')))
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname,'resources/views'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./image");
},
filename: function (req, file, cb) {
console.log(req.file);
cb(null, Date.now() + "-" + file.fieldname + ".png");
},
});
const upload = multer({ storage: storage });
app.post("/post", upload.single("image"), (req, res) => {
console.log(req.file);
});
app.get("/post", (req, res) => {
res.render("post");
});
app.listen(, () => {
console.log(`Example app listening at http://localhost:3000/login`);
});
You have few little bugs: first you forgot to add port and instead of login it should be post then we hit the correct address immediately, avoiding error Cannot GET /login
app.listen(3000, () => {
console.log(`Example app listening at http://localhost:3000/post`);
});
Project Folder & File structure:
app.js I added simple an error handler to the:
app.post("/post", upload.single("image"), (req, res, next) => {}
const path = require("path");
const express = require("express");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const multer = require("multer");
const app = express();
app.use(express.static(path.join(__dirname, "public")));
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "resources/views"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./image");
},
filename: function (req, file, cb) {
console.log(req.file);
cb(null, Date.now() + "-" + file.fieldname + ".png");
},
});
const upload = multer({ storage: storage });
// app.post("/post", upload.single("image"), (req, res) => {
// console.log(req.file);
// });
app.post("/post", upload.single("image"), (req, res, next) => {
const file = req.file;
if (!file) {
const error = new Error("Please upload a file");
error.httpStatusCode = 400;
return next(error);
}
res.send(file);
console.log("Success", req.file);
});
app.get("/post", (req, res) => {
res.render("post");
});
app.listen(3000, () => {
console.log(`Example app listening at http://localhost:3000/post`);
});
post.ejs
<form action="/post" id="formPost" method="post" enctype="multipart/form-data">
<input class="img-file" type="file" name="image" required />
<input class="submit" type="submit" value="Upload File" />
</form>
output:
after selecting the file and pressing upload file:
VSCode output:
Works like a charm ;-)

Image not showing from local storage on React with Multer and Node js

I've tried multer before in the past and it worked perfectly, but this time I can't get the image to load even when my path is correct and the file exists.
Here's my app.js on Node
require('dotenv').config();
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
const path = require('path')
app.use(express.urlencoded({ extended: true}));
app.use(express.json());
app.use('/tmp/my-uploads',express.static(path.join(__dirname,'/tmp/my-uploads')))
const routes = require('./routes');
app.use(routes);
app.listen(PORT, () => {
console.log('Listening on port : ', PORT);
})
Multer Middleware
const multer = require("multer");
const path = require("path");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./tmp/my-uploads");
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
cb(
null,
file.fieldname + "-" + uniqueSuffix + path.extname(file.originalname)
);
},
});
const upload = multer({ storage: storage });
module.exports = upload;
From my react front end to show the image
const image = CarsImages.filter((image) => {
if(image.primary === true){
return `http://localhost:3000/tmp/my-uploads/${image.filename}`;
}
})
Proof that the image exist, but doesnt load
screenshot
My local storage location
screenshot
Feel free to ask me further questions if you need more details

Upload image to S3 and read key values in req.body

I have this code block to upload image to S3
This is the image upload controller:
const multer = require('multer');
const multerS3 = require('multer-s3');
const AWS = require('aws-sdk');
let AWSConfig = require('./../config/awsconfig');
AWS.config.update({
accessKeyId: AWSConfig.S3_AKID,
secretAccessKey: AWSConfig.S3_SAK,
"region": AWSConfig.S3_REGION
});
exports.uploadWorkout = async (req, res) => {
req.setTimeout(0);
const s3 = new AWS.S3({ httpOptions: { timeout: 10 * 60 * 1000 }});
const singleUpload = multer({
storage: multerS3({
s3: s3,
bucket: AWSConfig.S3_BUCKET,
contentType: multerS3.AUTO_CONTENT_TYPE,
contentLength: req.body.length,
acl: 'public-read',
metadata: function(req, file, cb) {
cb(null, {fieldName: file.fieldname});
},
key: function(req, file, cb) {
cb(null, Date.now().toString()+'.'+file.originalname.split('.')[1]);
}
})
}).single('image');
await singleUpload(req, res, error => {
//const file = req.files; // files for array of files
const file = req.file; // file for single file
console.log("req.body >>>>>>>> ", req.body);
if(error) {
return res.status(400).send(error);
}
return res.status(200).send({imageurl: file.location});
});
}
This is the main App.js
// App.js
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(function(req, res, next) { //allow cross origin requests
res.setHeader("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
res.header("Access-Control-Max-Age", "3600");
res.header("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
next();
});
app.use(logger('dev'));
// app.use(express.json());
// app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(cors());
// rest of the error handling code ......
module.exports = app;
POSTMAN:
HEADERS:
Content-Type: application/octet-stream
x-amz-meta-fieldname: image
Authorization: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2Vybm9sh3rd9s212ddsfzdDFAZ21ha....
Image gets uploaded and I am getting imageurl as response but I am unable to get SomeKey and SomeValueSomeValueSomeValueSomeValue passed from Postman. What I get is req.body is empty object {} i.e. from console.log():
req.body >>>>>>>> {}

Entity is too large in node js version(express": "^4.17.1",)

I am trying to send 6 based64 images with some other data but I keep getting error entity is too large even I have added below code in my app.js file
`app.use(bodyparser.json({ limit: '50mb', extended: true }))
app.use(bodyparser.urlencoded({ limit: "50mb", extended: true, parameterLimit: 50000 }))`
If I try with the postman then there is no error only with web application.
I am using Angular as Front-end.
I don't know why this error is occurring.
Kindly your help would be great.
Thanks in Advance.
const express = require('express');
const bodyParser = require('body-parser')
const multer = require('multer')
var fs = require('fs');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './public');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now() + '.png');
}
});
var upload = multer({ storage: storage });
const app = express();
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.static('public'))
app.post('/', upload.single('file'), (req, res) => {
console.log(req.body.key1);
fs.readFile(req.file.path, function (err, data) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
res.end();
});
})
app.listen(3000);

GraphQL on azure server

I'm trying ti deploy a NodeJS App to Azure. Everything works fine including react. but when I'm trying to hit the GraphQL server I'm getting a 404 Error
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Any Ideas?
Here is my index.js
'use strict'
require('babel-core/register')
import schema from './data/schema'
import GraphQLHTTP from 'express-graphql'
import express from 'express'
const multer = require('multer')
const insert = require('./business/insert')
const app = express()
const port = process.env.PORT || 8080
var bodyParser = require('body-parser')
app.use(bodyParser.json()) // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })) // support encoded bodies
app.use('/graphql', GraphQLHTTP({
schema,
graphiql: true
}))
app.use(express.static('public'))
app.set('view engine', 'html')
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/upload/')
},
filename: function (req, file, cb) {
cb(null, Date.now() + '.xlsx')
}
})
var upload = multer({ storage: storage })
app.get('/', (req, res) => {
res.render('index')
})
app.listen(port, () => {
console.log('Listening http://localhost:8080')
})
Judging by this document https://babeljs.io/docs/usage/require/ it appears that tooling for ES6 only happens via the next requires
All subsequent files required by node with the extensions .es6, .es, .jsx and .js will be transformed by Babel.
So you'll need something like this instead:
// app.js
'use strict'
require('babel-core/register')
require('./index')
// index.js
import schema from './data/schema'
import GraphQLHTTP from 'express-graphql'
import express from 'express'
const multer = require('multer')
const insert = require('./business/insert')
const app = express()
const port = process.env.PORT || 8080
var bodyParser = require('body-parser')
app.use(bodyParser.json()) // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })) // support encoded bodies
app.use('/graphql', GraphQLHTTP({
schema,
graphiql: true
}))
app.use(express.static('public'))
app.set('view engine', 'html')
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/upload/')
},
filename: function (req, file, cb) {
cb(null, Date.now() + '.xlsx')
}
})
var upload = multer({ storage: storage })
app.get('/', (req, res) => {
res.render('index')
})
app.listen(port, () => {
console.log('Listening http://localhost:8080')
})

Resources