将所有multer上传的文件移动到Node.js中的新目标

时间:2018-08-04 11:55:33

标签: node.js express fs multer

我正在尝试创建一个具有两个字段的上传表单(选择要从您的PC上传的文件,以及一个在服务器的Folder1,Folder2,Folder3上具有两个目标的下拉菜单)。为此,我正在使用multer和express

我希望用户能够一次上传多个文件,并且用户具有一个下拉菜单来选择在服务器上存储文件的位置。由于用户将在表单中提供路径,因此我必须将文件上传到temp文件夹,然后将其移动到用户选择的目的地。

上传单个文件时,我发现了很多解决方案,但是我不知道如何处理多个文件。

这是我正在使用的代码

app.set('view engine', 'ejs');

app.get('/', (req, res) => {
    res.render('index');
});


var temppath = './uploads';


var storage = multer.diskStorage({
    destination: function (req, file, callback) {
        var dir = temppath;
        if (!fs.existsSync(dir)){
            fs.mkdirSync(dir);
        }
        callback(null, dir);
    },
    filename: function (req, file, callback) {
        callback(null, file.originalname);

    }
});

var fs = require('fs')

app.use( express.static( "public" ) );


var upload = multer({storage: storage}).array('files', 12);
app.post('/upload', function (req, res, next) {
    upload(req, res, function (err) {
        if (err) {
            return res.end("Something went wrong:(");
            //console.log (req.body);
        }
        res.end("Upload completed.");
        console.log (req.body.pathselector) ;
        //move file from tempfolder to choosen path
        //'req.body.pathselector' is the path that the user will choose from the upload form
        //sth like fs.rename from temppath/filename to req.body.pathselector/same_filename (no need to rename files);




    });
})

app.listen(3000);
console.log("runnig on :3000");

希望有人可以提供帮助,在此先感谢

1 个答案:

答案 0 :(得分:0)

我找到了解决方法。

基本上,您可以使用同一命令来移动单个文件,但是您将不得不遍历文件数组。

逻辑是:

res.end("Upload completed.");
        newDest = req.body.pathselector ;

        filesArray = req.files ;

        //move file from tempfolder to choosen path
        //'req.body.pathselector' is the path that the user will choose from the upload form
        //sth like fs.rename from temppath/filename to req.body.pathselector/same_filename (no need to rename files);

        for (var item in filesArray) {
        var oldPath = filesArray[item].path;
        // the delimiter is usually / but on windows it's \
        if ( os.platform() == 'Windows_NT'){
            var delimiterOFthisOS = '\\';
        }else{
            var delimiterOFthisOS = '/';
        }

        var newPath = newDest + delimiterOFthisOS + filesArray[item].filename ;

        fs.rename(oldPath, newPath, function (err) {
          if (err) throw err
          console.log('Successfully renamed - AKA moved!')
        })