【问题标题】:checking file size before uploading image using multer在使用 multer 上传图像之前检查文件大小
【发布时间】:2022-01-10 08:32:44
【问题描述】:

在将图像上传到磁盘之前,如何使用与图像传递相关的提交数据到服务器。这可能吗?如果没有,请给我另一个解决方案。
我想检查文件的大小,它应该至少为 4mp 分辨率,如果它的分辨率更小,则不应上传图像并发送错误消息

exports.uploadimg=(req,res,next)=>{
  
    uploadphoto(req, res, (err) => {
        if (err) {
            res.render("upload")
        }
        else {


    
            

          


           
            res.send("photo uloaded")
        }
    })

【问题讨论】:

    标签: javascript node.js file multer


    【解决方案1】:

    我认为您有一些多部分中间件(例如 connect-multiparty)读取 multipart/form-data 请求的请求负载。

    此中间件会在 request 对象 (request.files) 上为您提供 files 对象。 files 对象的属性是每个文件上传字段的键。每个此类属性的值可以是对象(单个文件上传)或数组(多个文件上传)。嵌套在 files 对象中的每个对象都具有描述实际上传文件的属性,并允许您在以下中间件中运行您认为合适的检查。

    // router declarations
    const {Router} = require('express');
    const multipart = require('connect-multipart');
    
    const multipartMiddleware = multipart();
    
    const validateFileSize = (file) => {
      /*
          Each file has the following property:
    
            fieldName - same as name - the field name for this file
            originalFilename - the filename that the user reports for the file
            path - the absolute path of the uploaded file on disk
            headers - the HTTP headers that were sent along with this file
            size - size of the file in bytes
        */
        // check against file size
        if (file.size < 4 * 1024 * 1024) throw new Error('File is too small');
    }
    
    const validateImageMiddleware = (req, res, next) => {
      // say we expected an upload field with key "productImage"
      const { files: { productImage } } = req;
      const isMultiple = Array.isArray(productImage);
      if (isMultiple) {
        productImage.forEach(validateFileSize);
      } else {
        validateFileSize(productImage);
      }
      // if we got here, the files were valid so we go to next handler
      next();
    };
    
    const myRouter = Router();
    myRouter.post('/expect-file', multipartMiddleware, validateImageMiddleware, (req, res) => {
      // do whatever you want to do
      res.send('Success');
    });

    【讨论】:

    • 我正在使用 multer 上传图片。但是它在获取buplkkoad之前不提供任何大小的图像。但是,如果我们在multer调用之外使用req对象,即在上传文件之前显示req.body为空,并且如果我们在multer调用内部使用,即在图像保存或上传req之后。 body 有所需的数据。
    • 因为我使用的是 multipart/form-data 可能会因为它而发生问题。你知道其他方法以便我可以解决上述问题,我也通过了类别,在上传之前我必须检查所属类别的图像,因此我必须将其保存到相应的图像文件夹中,我被困在这里帮助我。
    • 在路由器规范中放置 multer 中间件之后,您是否尝试过将 validateFileSize 函数(如上或根据需要实现)作为下一个中间件?
    • 检查req.file(如果是单张图片)或req.files(如果是多张图片)
    猜你喜欢
    • 2015-04-29
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多