Uploading file using multer, here is my code
var multer = require('multer');
var upload = multer({ dest: 'uploads/' });
app.post("/upload",upload.single('image'), api.uploadFile);
getting following error when uploading image file doing multi-part request
Error: Buffer.write(string, encoding, offset[, length]) is no longer supported
at Buffer.write (buffer.js:742:11)
at MultipartParser.initWithBoundary (D:\eclipse-workspace-oxy\ChatServer\node_modules\formidable\lib\multipart_parser.js:61:17)
at IncomingForm._initMultipart (D:\eclipse-workspace-oxy\ChatServer\node_modules\formidable\lib\incoming_form.js:308:10)
at IncomingForm._parseContentType (D:\eclipse-workspace-oxy\ChatServer\node_modules\formidable\lib\incoming_form.js:250:12)
at IncomingForm.writeHeaders (D:\eclipse-workspace-oxy\ChatServer\node_modules\formidable\lib\incoming_form.js:129:8)
at IncomingForm.parse (D:\eclipse-workspace-oxy\ChatServer\node_modules\formidable\lib\incoming_form.js:97:8)
at D:\eclipse-workspace-oxy\ChatServer\node_modules\connect\lib\middleware\multipart.js:125:12
Your stack trace shows that the problem comes from formidable, not multer.
A quick search on formidable's github open issues gives this.
Maybe try to run npm update.
Finally got the solution, need to add bodyParser for parse request bodies in a middleware.
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
it will work for Url Encoded requests. For Multi-part request, need to add middle ware like multer.
Related
I'm building a nodejs express webapp:
const express = require("express");
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
const app = express();
app.use(express.json({limit: '100mb'}));
app.use(express.urlencoded({ limit: '100mb',extended: true }));
in it I'm trying to upload an image and show it in the next page.
I'm using multer to upload the file and move it to a subdirectory of my public static folder I have set in express.
const path = require("path");
app.use("/static", express.static(path.join(__dirname, "public")));
That part works, the file is properly uploaded and moved, however when I try and access the image I get an error message:
Cannot GET /static/uploads/1/1655219221091/cover/Screenshot%202022-05-24%20at%2016.44.45.png
any clue to what I might be doing wrong? anyone else experiencing this? should I create a custom route to serve these files that technically aren't static?
linking it in html returns a 404
thanks
I'm trying to upload a file with connect-multiparty on my api but I can't make it works.
Here my code (a sample, because my api have a lot of working routes):
var express = require('express');
var bodyParser = require('body-parser');
var multipart = require('connect-multiparty');
var app = express();
var multipartMiddleware = multipart({ uploadDir: './imagesPath' });
// Define middleware
app.use(bodyParser.urlencoded({ extended: true })); // Support encoded bodies
app.use(bodyParser.json()); // Support json encoded bodies
var router = express.Router(); // Get an instance of the express Router
router.post('/testFileUpload', multipartMiddleware, function(req, res) {
console.log(req.body, req.files);
// Some other code
});
When I try to upload a file both req.body and req.files are empty {}
I know Body-Parser doesn't support multipart/form-data anymore so I'm trying to find a way to use it with another package but with no success so far.
I've tried with busboy, connect-busboy, multer, formidable, express-formidable, express-fileupload but everytime req.files is undefined, so I kinda feel I've make some progress with connect-multiparty by having req.files empty.
I've seen some topics with similar problems like this one, this one or this one but unfortunatly none of those helped me.
In client side I'm using Advanced REST Client and Postman.
Any ideas what I'm doing wrong ?
To whoever has this problem, I found removing the Content-Type headers on Postman with value "application/javascript" worked for me. I just hadn't noticed the whole time, while I tried different packages same as OP.
put enctype="multipart/form-data" in your tag form on html
I'm trying to POST multiple form fields, mixed with a file field, to my Node App, ver 7.4.0, using Express 4.0, but the fields aren't coming through to the server in the req object.
curl -X POST -H 'content-type: multipart/form-data' -F 'userEmail=my#gmail.com' -F upload=#/Users/me/Desktop/test_docs/doc1.xlsx localhost:5000/api/payments
But when I log console.log('REQ', req.body);, I get { }, when I expected at least userEmail present in the req.body.
I'm using bodyParser middleware as recommended
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true,
}));
Why isn't the form field coming through? Yet, if I post as application/JSON, I can see the fields in req.body.
According to the documentation of body-parser:
This does not handle multipart bodies, due to their complex and
typically large nature. For multipart bodies, you may be interested in
the following modules: busboy, connect-busboy, multiparty,
connect-multiparty, formidable, multer.
For example if multer:
// /api/payments.js
var express = require('express');
var router = express.Router();
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
/* POST /api/payments */
router.post('/payments', upload.single('upload'), function(req, res, next) {
res.json( req.body )
});
Express (or Connect's) bodyParser middleware is marked deprecated and users are advised to use instead:
app.use(connect.urlencoded())
app.use(connect.json())
However, when I run the an example from Node.js in Action, I use curl to fill out the form as suggested by the book:
curl -F entry[title]='Ho ho ho' -F entry[body]='santa loves you' http://abc:123#127.0.0.1:3000/api/entry
It doesn't work. req.body is not defined. Am I missing something? It works fine with bodyParser.
EDIT: SOLUTION as of Express 4
Parse json this way:
var bodyParser = require('body-parser');
...
app.use(bodyParser.json());
Parse urlencoded body this way:
app.use(bodyParser.urlencoded({extended: true}));
Then there is no deprecation warning. The extended: true (default) uses the qs module and false uses the querystring module to parse the body.
Don't use app.use(bodyParser()), that usage is now deprecated.
bodyParser is in fact the composition of three middlewares (see documentation and relevant source code): json, urlencoded and multipart:
json parses application/json request bodies
urlencoded parses x-ww-form-urlencoded request bodies
and multipart parses multipart/form-data request bodies, which is what you're interested in.
If you only specify json and urlencoded middlewares, the form data won't be parsed by any middleware, thus req.body won't be defined. You then need to add a middleware that is able to parse form data such as formidable, busboy or multiparty (as stated in connect's documentation).
Here is an example, using multiparty:
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
app.use('/url/that/accepts/form-data', multipartMiddleware);
app.post('/url/that/accepts/form-data', function(req, resp) {
console.log(req.body, req.files);
});
Don't forget that by using such middlewares you allow anyone to upload files to your server: it then your responsibility to handle (and delete) those files.
I can't seem to get the Express bodyParser function to work when sending a POST request with an image attached (with the Content-Type header set to multipart/form-data). The console.log in the code below simply returns {}. Any ideas?
var express = require("express");
var app = express();
app.use(express.bodyParser());
app.post("/photo", function(req, res) {
console.log(req.body);
});
app.listen(80);
You need to look at the req.files property for file uploads
http://expressjs.com/api.html#req.files
More info here:
http://howtonode.org/78e21b7d5503a5b2b372f6c2a5de077a1e809267/really-simple-file-uploads
If you're uploading the image using a file input then you might want to look at req.files instead -- if I understand correctly req.body only contains the POSTed fields that aren't files.