0

我在服务器中收到以下文件

{"file":{"size":6818,"path":"/tmp/a451340156a9986cd9d208678bdc40cf","name":"test.pdf","type":"application/pdf","mtime":"2014-09-03T15:26:25.733Z"}}

我有文件上传处理如下:

var form = new formidable.IncomingForm();
        form.parse(req, function(err, fields, files) {
        console.log(JSON.stringify(files));

            // `file` is the name of the <input> field of type `file`
            var old_path = files.file.path,
            file_size = files.file.size,
            file_ext = files.file.name.split('.').pop(),
            index = old_path.lastIndexOf('/') + 1,
            file_name = old_path.substr(index),
            new_path = path.join(process.env.PWD, '/uploads/', file_name + '.' + file_ext);
            fs.readFile(old_path, function(err, data) {
                fs.writeFile(new_path, data, function(err) {
                    fs.unlink(old_path, function(err) {
                        if (err) {
                            res.status(500);
                            res.json({'success': false});
                        } else {
                            res.status(200);
                            res.json({'success': true});
                        }
                    });
                });
            });
        });

这给出了 200 ok 但文件没有上传到所需的目录,即上传/

new_path is returned as /home/abc/myapp/uploads/0bc49fa19d15fb5bdf779c02d3cbc1d5.pdf

however it should just be /uploads/test.pdf
4

1 回答 1

0

是导致问题的路径还是文件名?

我将从使用重命名函数简化代码开始。它看起来像这样。

var newFilePath = path.join(process.env.PWD, 'uploads', files.file.name);
fs.rename(files.file.path,newFilePath,function(err){
  if(err){
     //handle error
  }
  res.json({success: 'true'});

});
于 2014-09-04T03:41:51.753 回答