jac*_*cky 2 javascript node.js express multer
我正在使用multer diskstorage将文件保存到磁盘。我首先将其保存到磁盘,并对文件进行一些操作,然后使用另一个函数和lib将其上传到远程存储桶。上传完成后,我想从磁盘上删除它。
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')
Run Code Online (Sandbox Code Playgroud)
这是我的使用方式:
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!");
})
})
});
Run Code Online (Sandbox Code Playgroud)
如何使用diskStorage删除功能删除temp文件夹中的文件? https://github.com/expressjs/multer/blob/master/storage/disk.js#L54
我决定将其模块化,并放入另一个文件中:
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 };
Run Code Online (Sandbox Code Playgroud)
不需要 Multer。只需使用此代码。
const fs = require('fs')
const path = './file.txt'
fs.unlink(path, (err) => {
if (err) {
console.error(err)
return
}
//file removed
})
Run Code Online (Sandbox Code Playgroud)
你并不需要使用multer要删除的文件,此外_removeFile是一个私有函数,你应该不使用。
您通常会通过删除文件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!")
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7400 次 |
| 最近记录: |