Comments (8)
Hi,
On line 75:
newFilePath = '/dev/null'; // do something for Windows!
You can use 'NUL' path for Windows like:
newFilePath = 'NUL';
You also can use os.platform()
to define current system.
By the way I don't see the reason to process files which have variable 'filename' equal to null (on line 66) sending them to '/dev/null'. Is it possible just to fill req.files
array like you do: req.files[fieldname] = file;
?
from multer.
Thanks for the 'NUL'. And you might have a point with not processing null
filename. It would be great if someone confirmed and send a pull request, if everything's fine.
from multer.
Any progress on this? My app crashes if a user submits a form without specifying a file. Or is there a way to override this?
from multer.
Hey, here's my version of index.js file of this package that works without crashes on empty file:
var os = require('os');
var fs = require('fs');
var path = require('path');
var crypto = require('crypto');
var Busboy = require('busboy');
var mkdirp = require('mkdirp');
module.exports = function(options) {
options = options || {};
// specify the destination directory, else, the uploads will be moved to the temporary dir of the system
var dest;
if (options.dest) {
dest = options.dest;
} else {
dest = os.tmpdir();
}
// make sure the dest dir exists
mkdirp(dest, function(err) {
if (err) throw err;
});
// renaming function for the uploaded file - need not worry about the extension
// ! if you want to keep the original filename, write a renamer function which does that
var rename = options.rename || function(fieldname, filename) {
var random_string = fieldname + filename + Date.now() + Math.random();
return crypto.createHash('md5').update(random_string).digest('hex');
};
return function(req, res, next) {
req.body = req.body || {};
req.files = req.files || {};
if (req.headers['content-type'] &&
req.headers['content-type'].indexOf('multipart/form-data') === 0 &&
(req.method === 'POST' || req.method === 'PUT')
) {
if (options.onParseStart) {
options.onParseStart();
}
// add the request headers to the options
options.headers = req.headers;
var busboy = new Busboy(options);
// handle text field data
busboy.on('field', function(fieldname, val, valTruncated, keyTruncated) {
if (req.body.hasOwnProperty(fieldname)) {
if (Array.isArray(req.body[fieldname])) {
req.body[fieldname].push(val);
} else {
req.body[fieldname] = [req.body[fieldname], val];
}
} else {
req.body[fieldname] = val;
}
});
// handle files
busboy.on('file', function(fieldname, fileStream, filename, encoding, mimetype) {
var ext, newFilename, newFilePath;
if (filename) {
ext = '.' + filename.split('.').slice(-1)[0];
newFilename = rename(fieldname, filename.replace(ext, '')) + ext;
newFilePath = path.join(dest, newFilename);
} else {
filename = null;
ext = null;
newFilename = null;
newFilePath = '/dev/null'; // do something for Windows!
}
var file = {
fieldname: fieldname,
originalname: filename,
name: newFilename,
encoding: encoding,
mimetype: mimetype,
path: newFilePath,
extension: (ext === null) ? null : ext.replace('.', ''),
size: 0,
truncated: null
};
if (filename) {
// trigger "file upload start" event
if (options.onFileUploadStart) {
options.onFileUploadStart(file);
}
var ws = fs.createWriteStream(newFilePath);
fileStream.pipe(ws);
fileStream.on('data', function(data) {
if (data) {
file.size += data.length;
}
// trigger "file data" event
if (options.onFileUploadData) {
options.onFileUploadData(file, data);
}
});
fileStream.on('end', function() {
file.truncated = fileStream.truncated;
req.files[fieldname] = file;
// trigger "file end" event
if (options.onFileUploadComplete) {
options.onFileUploadComplete(file);
}
});
fileStream.on('error', function(error) {
// trigger "file error" event
if (options.onError) {
options.onError(error, next);
} else next(error);
});
ws.on('error', function(error) {
// trigger "file error" event
if (options.onError) {
options.onError(error, next);
} else next(error);
});
} else {
req.files[fieldname] = file;
fileStream.resume();
}
});
busboy.on('partsLimit', function() {
if (options.onPartsLimit) {
options.onPartsLimit();
}
});
busboy.on('filesLimit', function() {
if (options.onFilesLimit) {
options.onFilesLimit();
}
});
busboy.on('fieldsLimit', function() {
if (options.onFieldsLimit) {
options.onFieldsLimit();
}
});
busboy.on('end', function() {
// when done parsing the form, pass the control to the next middleware in stack
if (options.onParseEnd) {
options.onParseEnd();
}
next();
});
req.pipe(busboy);
} else {
return next();
}
};
};
from multer.
Thanks! Just after I posted a comment here, I came up with the following solution by adding an onError handler to multer:
var multer = require("multer")({
dest: "./temp/",
rename: function (field, file) {
return Date.now() + " - " + field;
},
onError: function(error,next){
var message = error.message;
if(!message.indexOf("ENOENT"))next()
else next(error);
}
});
Basically, I just ignore any errors that begin with ENOENT.
from multer.
Good solution!
from multer.
+1
from multer.
Empty form fields are ignored.
from multer.
Related Issues (20)
- Error in uploading a photo in javascript using a multer. HOT 2
- There is a way to effectively add a custom Error handler to multer? HOT 2
- (love) Just to tell you how great your software is HOT 1
- TypeError: Cannot read properties of undefined (reading 'length') when fieldNameSize is not set HOT 6
- Upgrade to the latest version of busboy to prevent potential DOS attack via Dicer HOT 1
- File upload got stuck while uploading large text files HOT 3
- Upload file use Multer with Multer-gridfs-storage in environment of bun is not working but when I use environment of nodejs then it's working? HOT 1
- req.file returning Undefined on frontend, but with Insomnia returns correctly HOT 4
- Custom storage engine not working
- MulterError: Unexpected field when trying to use different storage configuration HOT 1
- Update Docs: Error: read ECONNRESET thrown during test using supertest, mocha but works fine while using postman. HOT 1
- Why does Multer does not release memory? HOT 1
- `preservePath` option not respected HOT 2
- This module only works with node 14 or LOWER HOT 39
- file.size undefined with multiple files HOT 2
- Request not finish when recieve an error HOT 11
- File upload middleware does not work when I chain it with other middlewares. I get req.file = undefined HOT 2
- bug: transfer-encoding HOT 2
- File type shows correct on the frontend but it changes to application/octet-stream on the backend HOT 1
- CVE-2022-24434: DoS affecting dicer (sub-dependency) HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from multer.