how to restrict file types with formidable js
Asked Answered
D

2

7

I have got a little function running with formidable to accept incoming files. It works like a charm, but i cannot see anywhere in the docs about restricting file types. https://github.com/felixge/node-formidable It seems almost everything else is covered except this.

Has anyone else come across this?

        var form = new formidable.IncomingForm(),
            files = [],
            fields = [],
            returnJson = {};

        //setup the incoming
        form.uploadDir = GLOBAL.server_settings.user_content;
        form.encoding = 'utf-8';
        form.maxFieldsSize = 2 * 1024 * 1024;
        form.maxFields = 1000;

        form.on('field', function(field, value) {
            console.log(field, value);
            fields.push([field, value]);
        })
        /* this is where the renaming happens */
        .on ('fileBegin', function(name, file){
            var fileType = file.type.split('/').pop();
            //rename the incoming file
            file.path = form.uploadDir + "/" + req.user.id + _ + toolbox.uniqid() + '.' + fileType;
        })
        .on('file', function(field, file) {
            //on file received
            console.log(field, file);
            files.push([field, file]);
        })
        .on('progress', function(bytesReceived, bytesExpected) {
            //self.emit('progess', bytesReceived, bytesExpected)
            var percent = (bytesReceived / bytesExpected * 100) | 0;
            process.stdout.write('Uploading: %' + percent + '\r');
        })
        .on('end', function() {
            console.log('-> upload done');
            console.log( files );
            console.log( fields );
            returnJson.file_data = files;
            returnJson.fields_data = fields;
            res.json( returnJson );
        });
        form.parse(req);
Distant answered 29/5, 2015 at 12:50 Comment(0)
D
5

So it turns out after playing around with it all.. if you just don't set the file path when the file type is not what you want this is the same as restricting my file type.

eg:

//event listeners for the form.parse() below
            form.on('field', function(field, value) {
                console.log(field, value);
                fields.push([field, value]);
            })
            /* this is where the renaming happens */
            .on ('fileBegin', function(name, file){
                var fileType = file.type.split('/').pop();
                if(fileType == 'jpg' || fileType == 'png' || fileType == 'jpeg' ){
                    //rename the incoming file
                    file.path = form.uploadDir + "/" + images_hash + '_' + image_count + '.' + fileType;
                    //increment image counter for next possible incoming image
                    ++image_count;
                } else {
                    console.log( 'incorrect file type: ' + fileType );
                }
            })
Distant answered 30/5, 2015 at 19:3 Comment(0)
F
6

You can do it by handling in form.onPart() function. Something like this:

fileTypes = ['image/jpeg', 'image/png', 'image/gif'];

form.onPart = part => {
    if (fileTypes.indexOf(part.mime) === -1) {
        // Here is the invalid file types will be handled. 
        // You can listen on 'error' event
        form._error(new Error('File type is not supported'));
    }
    if (!part.filename || fileTypes.indexOf(part.mime) !== -1) {
        // Let formidable handle the non file-pars and valid file types
        form.handlePart(part);
    }
};

form.parse(request).on('error', _err => {
    // You also pass it through next() to errorHandle function
    debug(_err.message); // output: File type is not supported
})

Hope it helped.

Floria answered 1/1, 2019 at 15:55 Comment(0)
D
5

So it turns out after playing around with it all.. if you just don't set the file path when the file type is not what you want this is the same as restricting my file type.

eg:

//event listeners for the form.parse() below
            form.on('field', function(field, value) {
                console.log(field, value);
                fields.push([field, value]);
            })
            /* this is where the renaming happens */
            .on ('fileBegin', function(name, file){
                var fileType = file.type.split('/').pop();
                if(fileType == 'jpg' || fileType == 'png' || fileType == 'jpeg' ){
                    //rename the incoming file
                    file.path = form.uploadDir + "/" + images_hash + '_' + image_count + '.' + fileType;
                    //increment image counter for next possible incoming image
                    ++image_count;
                } else {
                    console.log( 'incorrect file type: ' + fileType );
                }
            })
Distant answered 30/5, 2015 at 19:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.