nodejs multer diskstorage在保存到磁盘后删除文件

问题描述 投票:1回答:1

我正在使用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')

以下是我如何使用它:

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删除功能删除临时文件夹中的文件? 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 };
javascript node.js express multer
1个回答
3
投票

你不需要使用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!")
})
© www.soinside.com 2019 - 2024. All rights reserved.