Git Product home page Git Product logo

Comments (8)

pararuk avatar pararuk commented on April 27, 2024

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.

hacksparrow avatar hacksparrow commented on April 27, 2024

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.

RangerMauve avatar RangerMauve commented on April 27, 2024

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.

pararuk avatar pararuk commented on April 27, 2024

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.

RangerMauve avatar RangerMauve commented on April 27, 2024

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.

pararuk avatar pararuk commented on April 27, 2024

Good solution!

from multer.

doberkofler avatar doberkofler commented on April 27, 2024

+1

from multer.

hacksparrow avatar hacksparrow commented on April 27, 2024

Empty form fields are ignored.

from multer.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.