使用Formidable创建新文件夹

时间:2016-11-17 16:45:45

标签: node.js express formidable

我有下一个代码:

router.post('/subirArchivo', function (req, res){
var form = new formidable.IncomingForm();

form.parse(req);

form.on('fileBegin', function (name, file){
    file.path = path.join(__dirname,'../../../../uploads/', file.name);

});

form.on('file', function (name, file){
    console.log('Uploaded ' + file.name);
});

res.sendFile(path.join(__dirname,'../../../client/views/faseVinculacion', 'busquedaVinculacion.html'))

上传文件没关系,但是,如何创建一个不存在的新文件夹?

1 个答案:

答案 0 :(得分:1)

首先你需要添加fs-extra(更简单的方法)
并在你的帖子中,添加:

fs.mkdirsSync(__dirname + '/../public/dist');
form.uploadDir = __dirname + '/../public/dist';

更多细节:

if (req.url == '/upload') {
    var form = new formidable.IncomingForm(),
        files = [],
        fields = [];

    fs.mkdirsSync(__dirname + '/../public/dist');
    form.uploadDir = __dirname + '/../public/dist';


    form
      .on('field', function(field, value) {
        console.log(field, value);
        fields.push([field, value]);
      })
      .on('file', function(field, file) {
        console.log(field, file);
        files.push([field, file]);
      })
      .on('end', function() {
        console.log('-> upload done');
        res.writeHead(200, {'content-type': 'text/plain'});
        res.write('received fields:\n\n '+util.inspect(fields));
        res.write('\n\n');
        res.end('received files:\n\n '+util.inspect(files));
      });
    form.parse(req);
  }