2017-07-23 140 views
3

送到我要上傳文件到請求中指定的(在名稱字段)的文件夾名稱我嘗試添加req.body.name但未定義 這是代碼更改文件夾名稱,以強大的名稱要求

var mongoose = require('mongoose'); 
var DataBase = require('../models/resource').DataBase; 
var formidable = require('formidable'), 
    http = require('http'), 
    util = require('util'); 
var mkdirp = require('mkdirp'); 
var fs = require('fs'); 
exports.upload = function (req, res) { 
var uploadDir = './uploads/databses/'+req.body.name; 
mkdirp(uploadDir, function (err) { 
    if (err) return cb(err); 
    var form = new formidable.IncomingForm({ 
    uploadDir: uploadDir, 
    keepExtensions: true 
}); 
form.on('progress', function(bytesReceived, bytesExpected) { 
    console.log(100 * bytesReceived/bytesExpected + '%'); 
}); 
form.parse(req, function(err, fields, files) {  
     res.writeHead(200, { 
      'content-type': 'text/plain' 
     }); 
     res.write('received upload:\n\n'); 
     res.end(util.inspect({ 
      fields: fields, 
      files: files 
     })); 
    }); 

}); 
}; 
+0

使用身體解析器解析你的預期要求。 https://github.com/expressjs/body-parser – Burdy

回答

3

解決方案,我發現的是我創建的文件夾移動到新的

 var uploadDir = './uploads/databses/temp/'; 

     var form = new formidable.IncomingForm({ 
     uploadDir=uploadDir,  
     keepExtensions: true 
     }); 
     form.on('progress', function(bytesReceived, bytesExpected) { 
     console.log(100 * bytesReceived/bytesExpected + '%'); 
     }); 
     form.parse(req)  
     .on('field', function(name, fields) { 
     var body = JSON.parse(fields); 

     uploadDir='./uploads/databses/'+body.nameOfFolder+'/'; 
     form.uploadDir=uploadDir; 
     }).on('file', function(name, files) { 
     //moving temp to new folder 
     mv('./uploads/databses/temp', form.uploadDir, {mkdirp: true}, 
     function(err) { 

     }); 
     res.end(util.inspect({ 
     files: files 
     })); 
     }) 
     .on('error', function(err) { 
     next(err); 
     }) 
     .on('end', function() { 
     res.end(); 
     });