Expressjs upload files, check if the file was actually sent, specify the maximum file size and save its name

Working with expressjs after about a month, I came across a file upload problem. Despite consulting with Google and various blogs, I did not find the answer to the following three questions:

What I need to do / what settings for bodyParser I need to choose in order to:

  • Make sure that the file is actually uploaded (currently, when you submit the form without selecting a file, an empty file is created).

  • Where can I specify a value for the maximum size allowed for a file?

  • How can I omit renaming a file?

I am currently including bodyParser in my application (v. 3.0.0) with the following option:

{keepExtensions: true, uploadDir: __dirname + '/public/uploads'} 
+6
source share
2 answers

I recently encountered a similar problem. for question number 2, check http://www.senchalabs.org/connect/middleware-limit.html

app.use(express.limit('4M')); // in your app.configure()

 app.post('/upload', function(req, res) { var fs = require('fs'), file = req.files.myfile; //your file field; if(file.size === 0) { // question #1 fs.unlinkSync(file.path); res.redirect('/error?'); } else { //question #3 var fn = file.path.split('/'); fs.rename(file.path, file.path.replace(fn[fn.length-1], file.name)); res.redirect('/success?'); } }); 
+4
source

About your concern

Make sure that the file was actually uploaded (currently, when you submit a form without selecting a file, an empty file is created).

After a long search I found a great solution

First you need to install node-formidable

Then after turning on the library, to check if the file is loaded first

 var form = new formidable.IncomingForm(); form.parse(req, function(err, fields, files) { if (Object.keys(files).length !== 0) { console.log("File is exist") } else { console.log("File is not exist") } }); 

And about the size you can check.

 form.maxFieldsSize = 2 * 1024 * 1024; 

Sincerely.

Abdulaziz Nur

+1
source

Source: https://habr.com/ru/post/922064/


All Articles