Move File in ExpressJS/NodeJS

前端 未结 4 1944
执笔经年
执笔经年 2021-01-04 18:50

I\'m trying to move uploaded file from /tmp to home directory using NodeJS/ExpressJS:

fs.rename(\'/tmp/xxxxx\', \'/home/user/xxxxx\         


        
4条回答
  •  天涯浪人
    2021-01-04 19:21

    Another way is to use fs.writeFile. fs.unlink in callback will remove the temp file from tmp directory.

    var oldPath = req.files.file.path;
    var newPath = ...;
    
    fs.readFile(oldPath , function(err, data) {
        fs.writeFile(newPath, data, function(err) {
            fs.unlink(oldPath, function(){
                if(err) throw err;
                res.send("File uploaded to: " + newPath);
            });
        }); 
    }); 
    

提交回复
热议问题