【问题标题】:Node/express - cancel multer photo upload if other fields validation failsNode/express - 如果其他字段验证失败,则取消多张照片上传
【发布时间】:2023-02-04 07:36:13
【问题描述】:

在编辑用户功能之前,我有 multer 作为中间件。问题是 multer 无论如何都会上传照片,所以我想知道是否有办法以某种方式取消上传,例如电子邮件无效。如果编辑功能中存在验证错误,我尝试通过 fs.unlink 功能删除上传的图像,但我收到“EBUSY:资源繁忙或锁定,取消链接”错误。我想当我尝试删除图像时,multer 会同时上传。 任何想法如何解决这个问题?

【问题讨论】:

    标签: node.js express multer node.js-fs


    【解决方案1】:

    在你的函数上创建一个 try/catch 块并处理错误抛出

    import { unlink } from 'node:fs/promises';
    import path from 'path'
    
    // code ...
    
    // inside your function
    
    const img  = req.file // this needs to be outside the try block
    
    try {
    
         // your code, throw on failed validation
    
    } catch (e) {
       if (img) {
            // depends on where you store in multer middleware
            const img_path = path.resolve(YOUR_PATH, img.filename) 
            await unlink(img_path);
    
            console.log(`deleted uploaded ${ img_path }`);
        }
    
        // revert transaction or anything else
    }
    

    【讨论】:

      【解决方案2】:

      如今,应用程序通常将上传文件 API 与数据操作 API 分开,以实现预览/编辑图像等功能。稍后,他们可以运行后台作业来清理未使用的数据。

      但是如果你的情况有必要,我们可以使用 multer 的内置 MemoryStorage 先将文件数据保存在内存中,然后在验证完成后将其保存到磁盘。

      const express = require('express');
      const app = express();
      
      const multer = require('multer');
      const storage = multer.memoryStorage();
      const upload = multer({ storage });
      const fs = require('fs');
      
      app.post("/create_user_with_image", upload.single('img'), (req, res) => {
        // Validation here
      
        fs.writeFile(`uploads/${req.file.originalname}`, req.file.buffer, () => {
          res.send('ok');
        });
      });
      

      笔记:正如 multer 文档所说,此解决方案可能会导致您的应用程序在上传非常大的文件或大量相对较小的文件时很快耗尽内存。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-03
        • 1970-01-01
        • 2020-01-13
        • 2020-05-15
        • 1970-01-01
        • 1970-01-01
        • 2013-07-28
        • 1970-01-01
        相关资源
        最近更新 更多