【问题标题】:Is there a way to save two image at once only using one field?有没有办法只使用一个字段一次保存两个图像?
【发布时间】:2018-09-30 11:53:16
【问题描述】:

我想保存两张原始图片,一张调整大小(用于缩略图)

我只使用一个字段作为图像

但我认为 multer 已经在 S3 上保存了原始文件,所以我无法在 S3 上保存调整大小的文件。

有没有办法只使用一个字段一次保存两个图像?

const single = upload.single('img')

 single(req, res, function (err) {
            if (err) {
                return res.status(400).json({
                    message: errorMessage.UNEXPECTED_FIELD_ERROR + ' (img)'
                })
            }

            let img = req.file //img is already stored on S3 
                            //Now I can't store my thumbnail on S3!

gm(request(img.location))
          .thumbnail('50', '50', '!')
          .stream(function (err, stdout, stderr) {
            if(err) console.log(err)

            var writeStream = fs.createWriteStream('/tmp/resized.jpg');
            stdout.pipe(writeStream);
          });
          //...

【问题讨论】:

    标签: mongodb amazon-s3 multer


    【解决方案1】:

    https://www.npmjs.com/package/multer-s3-transform#transforming-files-before-upload

    var upload = multer({
      storage: multerS3({
        s3: s3,
        bucket: 'some-bucket',
        shouldTransform: function (req, file, cb) {
          cb(null, /^image/i.test(file.mimetype))
        },
        transforms: [{
          id: 'original',
          key: function (req, file, cb) {
            cb(null, 'image-original.jpg')
          },
          transform: function (req, file, cb) {
            cb(null, sharp().jpg())
          }
        }, {
          id: 'thumbnail',
          key: function (req, file, cb) {
            cb(null, 'image-thumbnail.jpg')
          },
          transform: function (req, file, cb) {
            cb(null, sharp().resize(100, 100).jpg())
          }
        }]
      })
    })
    

    我使用了 multer-s3-transform 提供的转换,但最新版本不提供转换选项,所以我使用此代码副本并粘贴到我的 multer-s3-transform 库中

    https://github.com/badunk/multer-s3/pull/56/files

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-12
      • 2019-01-29
      • 1970-01-01
      • 2016-10-23
      • 1970-01-01
      相关资源
      最近更新 更多