nodejs multer diskstorage保存到磁盘后删除文件 [英] nodejs multer diskstorage to delete file after saving to disk
问题描述
我正在使用multer磁盘存储将文件保存到磁盘.我首先将其保存到磁盘,并对文件进行一些操作,然后使用另一个函数和lib将其上传到远程存储桶.上传完成后,我想从磁盘上删除它.
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.
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')
这是我的用法:
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!");
})
})
});
我如何使用diskStorage删除功能删除temp文件夹中的文件? https://github.com/expressjs/multer/blob/master/storage/disk.js#L54
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
我决定将其模块化,并将其放入另一个文件中
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 };
推荐答案
您无需使用 multer
删除文件,并且 _removeFile
是私有函数您不应该不使用.
You don't need to use multer
to delete the file and besides _removeFile
is a private function that you should not use.
您通常会通过 fs.unlink
.因此,只要您可以访问 req.file
,您都可以执行以下操作:
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:
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!")
})
这篇关于nodejs multer diskstorage保存到磁盘后删除文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!