javascript nodejs multer diskstorage 保存到磁盘后删除文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49099744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
nodejs multer diskstorage to delete file after saving to disk
提问by Hymany
I am using multer diskstorage to save a file to disk. I first save it to the disk and do some operations with the file and then i upload it to remote bucket using another function and lib. Once the upload is finished, i would like to delete it from the disk.
我正在使用 multer diskstorage 将文件保存到磁盘。我首先将它保存到磁盘并对该文件进行一些操作,然后我使用另一个函数和库将它上传到远程存储桶。上传完成后,我想将其从磁盘中删除。
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/tmp/my-uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({ storage: storage }).single('file')
and here is how i use it:
这是我如何使用它:
app.post('/api/photo', function (req, res) {
upload(req, res, function (err) {
uploadToRemoteBucket(req.file.path)
.then(data => {
// delete from disk first
res.end("UPLOAD COMPLETED!");
})
})
});
how can i use the diskStorage remove function to remove the files in the temp folder? https://github.com/expressjs/multer/blob/master/storage/disk.js#L54
如何使用 diskStorage 删除功能删除临时文件夹中的文件? https://github.com/expressjs/multer/blob/master/storage/disk.js#L54
update:
更新:
I have decided to make it modular and put it in another file:
我决定将其模块化并将其放入另一个文件中:
const fileUpload = function(req, res, cb) {
upload(req, res, function (err) {
uploadToRemoteBucket(req.file.path)
.then(data => {
// delete from disk first
res.end("UPLOAD COMPLETED!");
})
})
}
module.exports = { fileUpload };
回答by Francisco Mateo
You don't need to use multerto delete the file and besides _removeFileis a private function that you should notuse.
你并不需要使用multer要删除的文件,此外_removeFile是一个私有函数,你应该不使用。
You'd delete the file as you normally would via fs.unlink. So wherever you have access to req.file, you can do the following:
您可以像往常一样通过fs.unlink. 因此,无论您在何处可以访问req.file,都可以执行以下操作:
const fs = require('fs')
const { promisify } = require('util')
const unlinkAsync = promisify(fs.unlink)
// ...
const storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, '/tmp/my-uploads')
},
filename(req, file, cb) {
cb(null, `${file.fieldname}-${Date.now()}`)
}
})
const upload = multer({ storage: storage }).single('file')
app.post('/api/photo', upload, async (req, res) =>{
// You aren't doing anything with data so no need for the return value
await uploadToRemoteBucket(req.file.path)
// Delete the file like normal
await unlinkAsync(req.file.path)
res.end("UPLOAD COMPLETED!")
})

