2015-05-29 68 views
1

我有一個強大的接受傳入文件的小函數。它就像一個魅力,但我無法看到有關限制文件類型的文檔中的任何地方。 https://github.com/felixge/node-formidable 似乎幾乎所有的東西都被覆蓋,除了這個。如何用強大的js限制文件類型

有沒有人遇到過這個?

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

回答

2

所以,這一切玩了..如果你只是在文件類型是不是你想要的,這是一樣的限制我的文件類型沒有設置文件路徑後證明。

如:

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