【问题标题】:Is there a way to delete a multer file after a certain amount of time?有没有办法在一定时间后删除 multer 文件?
【发布时间】:2021-10-08 13:38:37
【问题描述】:

我已将 multer 设置为将图像存储在临时文件夹中,通过 POST 请求将其发送到 Imgur,然后 POST 请求通过 fs.unlink('path') 将其从文件夹中删除。我担心会发生未知错误或崩溃或某些事情,并且一堆图像会卡在临时文件夹中。我可以到处设置一堆fs.unlink,但我想知道是否有办法设置multer,以便在x 时间后删除文件。

这是我的 multer 设置的样子:

const storage = multer.diskStorage({
  destination: './public/uploads/',
  filename: function(req, file, cb){
    cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
  }
});

// Init Upload Multer
const upload = multer({
  storage: storage,
  limits:{fileSize: 20000000},
  fileFilter: function(req, file, cb){
    checkFileType(file, cb);
  }
  //Do some function here?
}).single('myImage');

这是基本的 POST:

app.post('/upload-image', (req, res) => {
  upload(req, res, (err) => {
    if (err) {
      console.log(err)
    } else {
      if (req.file == undefined) {
        console.log('Error: No File Selected')
      } else {
        imgur
          .uploadFile(`./public/uploads/${req.file.filename}`)
          .then((json) => {

           //I do some stuff with the json and mongodb then:
           fs.unlink(`./public/uploads/${req.file.filename}`, (err) => {
              if (err) {
                console.error(err)
                return
              }
              console.log('file deleted')
            })
          })
          .catch((err) => {
            console.error(err.message);
          });
      }
    }
  });
})

有什么想法可以确保我不会在临时文件夹中获得一堆额外的图像吗?

【问题讨论】:

  • 最简单的方法是 1) 使用一些前缀设置文件名,指示文件的创建时间 2) 有一个计划/cron 作业将检查临时文件夹,并删除基于那个前缀
  • @PK214 你知道任何关于创建计划/cron 作业的好教程吗?

标签: node.js express multer


【解决方案1】:

这是我的 deletePost 控制器...

exports.deletePost = async (req, res, next) => {
  const postId = req.params.postId;
  try {
    const post = await Post.findById(postId);

    if (!post) {
      const error = new Error("Could not find post.");
      error.statusCode = 404;
      throw error;
    }
    if (post.creator.toString() !== req.userId) {
      const error = new Error("Not authorized!");
      error.statusCode = 403;
      throw error;
    }
    // Check logged in user
    clearImage(post.imageUrl);
    await Post.findByIdAndRemove(postId);

    const user = await User.findById(req.userId);
    user.posts.pull(postId);
    await user.save();

    res.status(200).json({ message: "Deleted post." });
  } catch (err) {
    if (!err.statusCode) {
      err.statusCode = 500;
    }
    next(err);
  }
};

这是我的clearImage 函数... 在删除图像控制器中使用此功能...

const clearImage = (filePath) => {
  filePath = path.join(__dirname, "..", filePath);
  fs.unlink(filePath, (err) => console.log(err));
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多