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

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)

sqr*_*nts 9

不需要 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)


Fra*_*teo 6

你并不需要使用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)

  • 这是一个很棒的解决方案。+1 用于使用美化,+1 用于指出我们只需要取消链接 `req.file.path`。我刚刚学到了两件新东西(在看到这个之前,从昨天开始手动包装 fs 方法在承诺中与 async-await 一起使用)。 (2认同)