【问题标题】:how to restrict file types with formidable js如何使用强大的 js 限制文件类型
【发布时间】:2015-05-29 12:50:31
【问题描述】:

我有一个运行强大的小功能来接受传入的文件。它就像一个魅力,但我在文档中看不到任何关于限制文件类型的地方。 https://github.com/felixge/node-formidable 似乎几乎所有其他内容都涵盖了这一点。

还有其他人遇到过这个吗?

        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);

【问题讨论】:

    标签: node.js file-upload formidable


    【解决方案1】:

    所以在玩了所有之后结果证明..如果您只是在文件类型不是您想要的时候不设置文件路径,这与限制我的文件类型相同。

    例如:

    //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 );
                    }
                })
    

    【讨论】:

      【解决方案2】:

      您可以通过处理 form.onPart() 函数来做到这一点。像这样的:

      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
      })
      

      希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 2022-08-05
        • 1970-01-01
        • 2010-12-30
        • 2012-12-06
        • 2015-02-15
        • 1970-01-01
        • 2012-02-27
        • 2011-09-21
        • 1970-01-01
        相关资源
        最近更新 更多