Having trouble uploading a file with node using multer - node.js

This seems like a simple problem, but I've been spending a while trying to solve it and I can't quite figure out what's wrong. This is my frontend form that is making the request:
div#PreGA
p PreGa.json:
form(action="config/set/PreGa", name="pre-ga", method="post", enctype="multipart/form-data")
input(type="file" value="Choose File" accept=".json")#choose-file-pre-ga
input(type="submit" value="Upload")#upload-pre-ga
This is the route that should receive the request:
var upload = multer({ dest: 'uploads/' });
//set the JSON file for the pre-ga reported issues
router.post('/config/set/PreGa',ensureAuthenticated, upload.single('pre-ga'), function(req, res, next) {
console.log(req.body);
console.log(req.file);
});
The issue is that req.file, which should return the file, is undefined when the route is called.
This is one of the simplest use cases, and I can't figure out what's going wrong. It would greatly appreciate some help.

Your file input is missing a name attribute.

Related

Multer gives unexpetcted end of form error

The file is being send to the nodejs server, but the upload.single gives an unexpected end of form error. How do i fix this?
const upload = multer({ dest: "../../uploaded_images" });
router.patch("/profile", upload.single("profileImage"), (req, res) => {
console.log(req.files) // This shows that there is a file named profileImage, I can see that when I remove the upload.single("profileImage")
res.send("")
})
the file structure:
It seems to be a bug in Multer itself. I solved by downgrading Multer to 1.4.3.
See https://github.com/expressjs/multer/issues/1144

Why am I NOT able to upload files with the following NodeJS code?

I am trying to design a simple app in NodeJS that uploads a CSV file via an HTML form.
Having carefully followed this tutorial on YouTube on how to upload files using NodeJS, I don't understand why my code isn't able to upload any file. I haven't gotten further than 6:53 mins in the youtube tutorial.
Find below my simple code:
const express = require('express');
const app = express();
const multer = require('multer');
const fileStorageEngine = multer.diskStorage({
destination: (req,file,cd)=> {
cd(null, './uploads')
},
filename: (req,file,cb)=>{
cb(null, Date.now() + '--' + file.originalname);
},
});
const upload = multer({storage: 'fileStorageEngine'});
app.get('/', (req,res)=> {
res.sendFile(__dirname +'/testDir/form.html' );
});
app.post('/uploads', upload.single('file'), (req, res)=> {
console.log(req.file);
res.send('Single File Upload Success!');
});
app.listen('3600', ()=> console.log('App is listening...'));
...and my HTML form code looks like this:
http://localhost:3600/ correctly displays
I am able to browse to whatever file I choose, and clicking on the submit button that gets me directed to:
According to the YouTube at 6:53 mins, the uploads folder should now contain the uploaded file,
however, the folder is empty!
Also, the terminal displays
...suggesting that console.log(req.file); no file was actually read in.
I also tried using postman and this is a screenshot of the result:
I have tried to re-watching the video and carefully followed the instructions but still haven't been able to resolve the issue.
Kindly help me understand why the upload isn't working and how to resolve this issue.
Looking forward to your help.
You have set the storage field as a string instead of a multer.diskStorage object.
Change it to: const upload = multer({storage: fileStorageEngine});
Also make sure that the key value in Postman form-data is set to file, because you are using upload.single('file')
Make sure you have enctype="multipart/form-data" in your html form. Also, make sure you have set name correctly. Can you paste the code for your form as well?

How to handle binary post data in Express?

I am wanting to post an image in the form of binary to my Express app.
I'm assuming it should come through in the req.body object but will need some form of middleware to be able to handle binary data?
When I send an image as binary from postman and try log req.body, the object is empty.
I am using express-generator as a boilder plate which comes with body-parser like so:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
I had a look at Multer but think that is just for multipart data
Also looked at busboy but couldn't figure out if that will handle binary data.
Am I correct that the post data will still come through in req.body?
And what middleware do I need to handle binary data?
Thanks
The method I ended up using:
const multer = require('multer')
const storage = multer.memoryStorage()
const upload = multer({ storage: storage })
router.post('/upload', upload.single('image'), function(req, res, next) {
const image = req.file.buffer
});
Unfortunately, you can't use the body-parser to handle the binary data like files and stuff like that. But wut you can do is use a module call formidable to handle this
Example snipper
app.post('/', (req, res) => {
const form = new formidable.IncomingForm();
form.parse(req, (error, fields, files) => {
if(error){
console.log(error)
}
console.log(fields.name)
const cuteCat = files.cat_image;
console.log(cuteCat.name) // The origin file name
console.log(cuteCat.path) // The temporary file name something like /tmp/<random string>
})
});
<input name="cat_image" type="file" />
<input name="name" type="text" />

How do I get the body of a request from npm's multer if I don't upload a file?

I have a Node server using express.
I was originally using body-parser, but that doesn't allow for file uploads. So, I switched to multer (the easiest integration with express). However, in order to get any of the req (specifically req.body), this is my code:
var multer = require('multer');
var upload = multer({ dest : 'uploads/' });
server.all('/example', function (req, res, next) {
var up = upload.single('photo')
up(req, res, function(err) {
console.log(req.body); // I can finally access req.body
});
}
The problem with this, is that not all of my routes need to upload a file. Do I need to waste the CPU on calling upload.single() for each route in order to get access to the body? upload.single('') ends up not uploading any file, but it's still precious time spent on the main thread.
It appears that upload.single() waits for the callback, so it may not be as big of a deal as I'm making it, but I don't like calling functions when I don't have to.
Is there a way around calling upload.single(), or am I just making a bigger deal out of this than it really is?
For text-only multipart forms, you could use any of the multer methods, which are .single(), .array(), fields()
For instance using .array()
var multer = require('multer');
var upload = multer({ dest : 'uploads/' });
server.all('/example', upload.array(), function (req, res, next) {
console.log(req.body);
});
It doesn't really matter which you use, as long as it's invoked without arguments Multer will only parse the text-fields of the form for you, no files

Nodejs multipart/form-data dont let upload files

Problem
I have a server that needs to upload files, I have tried multiparty, connect-multiparty and multer.
But every case, has the same problem: the file only uploads some times, i mean, i could send a file and there is a chance that the libraries don't parse the files, and never continue the code, resulting on not uploading the files.
In a While, the request send an error "Request Aborted", but its the normal response when the request time out
This is the problematic node.js file:
var multiparty = require('multiparty');
var multer = require('multer');
var upload = multer({
dest: "/uploads/"
});
///----rest of code----
//1. Multiparty
app.post("/upload",[function(req, res){
var form = new multiparty.Form({uploadDir:'/uploads/'});
console.log("to upload")
form.parse(req, function (err, fields, files) {
console.log("uploaded");
res.json({uploaded: true});
})
}]
//2. multer
app.post("/upload2",[
function(req, res, next){
console.log("to upload");
next();
},
upload.fields([
{name: "file"},
{name: "thumbnail"}
]),
function(req, res){
console.log("uploaded");
res.json({uploaded: true});
}]
Make sure your form looks like this
<form enctype="multipart/form-data" action="..." method="...">
...
</form>
And to be honest you will be better off using node-formidable. It is the most used multipart/form-data package on npm.
The example works straight out of the box.
Cheers
https://stackoverflow.com/a/23975955/4920678
I was using the setup from this answer, to use http and https over the same Port.
Turns out, the setup with that proxy damaged the packages that where too large or something, and then the files never get parsed

Resources