【问题标题】:multer: How to process and manipulate files before saving?multer:如何在保存之前处理和操作文件?
【发布时间】:2021-08-07 12:20:04
【问题描述】:

我想在保存之前使用sharp 处理图像,所以我不需要保存文件两次(一次是multer,一次是sharp)。我发现的最好的方法是用不带参数的初始化 multer 将文件保存在内存中:

const upload = multer()

然后在路由处理程序中将文件缓冲区提供给锐化:

await sharp(req.file.buffer)
        .resize(500)
        .jpeg({ quality: 50 })
        .toFile(path)
        );

如果有更好的方法告诉我。

更好的问题是: 在保存之前调用multer中是否有类似钩子的东西?所以我可以在保存之前更改文件内容。

【问题讨论】:

    标签: node.js multer sharp


    【解决方案1】:

    这个过程是从fileFilter方法开始,然后是multer的fileName,所以你应该开始在fileFilter中调整它的大小,将它保存到临时目录,然后在调整大小后重新调整图像,你可以使用sharp包的.ToFile方法,它将把目的地保存在.toFile( “./上传”) file-mapper.ts(用于返回另一个对象)

    export const fileMapper = ({ file, req }: FileMapper) => {
      if (!file) {
        return null!;
      }
      const fileName = editFilename(req.file);
      const image_url = `${req.protocol}://${req.headers.host}/${req.file.destination}/${fileName}`;
      resizeImage(req, fileName);
      return {
        filename: file.filename,
        image_url,
        path: file.path,
      };
    };
    

    我的 resize-image.ts

    import { Request } from 'express';
    import path from 'path';
    import sharp from 'sharp';
    import fs from 'fs';
    export const resizeImage = async (req: Request, fileName: string) => {
      await sharp(req.file.path)
        .resize({ height: 700, width: 700, position: 'center' })
        .jpeg({ quality: 90, chromaSubsampling: '4:4:4' })
        .toFile(path.resolve(req.file.destination, fileName))
        .then((sharpOutPut) => {
          if (sharpOutPut) fs.unlinkSync(req.file.path);
        })
        .catch((err) => {
          throw err;
        });
    };
    

    磁盘存储.ts

    const storage= diskStorage({
            destination: 'upload/product',
            filename: editFileName,
          }),
          fileFilter: imageFileFilter,
        })
    
    • 在multer的fileFilter中使用sharp
    • 我正在使用 fileMapper,因为我想为我的数据库接收新对象

    【讨论】:

      猜你喜欢
      • 2011-02-17
      • 2016-07-08
      • 1970-01-01
      • 1970-01-01
      • 2017-10-12
      • 1970-01-01
      • 2020-12-06
      • 1970-01-01
      • 2017-02-05
      相关资源
      最近更新 更多