具有锐利上传和调整大小的 Multer-S3

Multer-S3 with sharp upload and resize

我已经能够使用 multer-s3 library but now I'm trying to add the sharp 库将图像文件上传到 s3 以调整大小和旋转,但无法弄清楚它需要去哪里或如何去。这是我当前用于上传的代码:

var options = {
'endpoint' : 'https://xxx',
'accessKeyId' : '123',
'secretAccessKey' : '123abc',
'region' : 'xxx'
};

 const s3 = new aws.S3(options);

const upload = multer({
storage: multerS3({
    s3: s3,
    bucket: 'wave',
    acl: 'public-read',
    metadata: function (req, file, cb) {
      cb(null, Object.assign({}, req.body));
    },
    key: function (request, file, cb) {
        console.log('inside multerS3',file);
        cb(null, file.originalname);
    }
})
}).array('file', 1);

app.post('/upload/', (req,res) => {
   upload(req,res, async function (error) {
     if(error){
        res.send({ status : error });
     }else{
        console.log(req.files[0]);
        res.send({ status : 'true' });
     }
    });
 });

并对文件执行类似的操作:

 sharp(input)
 .resize({ width: 100 })
 .toBuffer()
 .then(data => {
   // 100 pixels wide, auto-scaled height
 });

任何帮助将不胜感激:)

好的,所以我从来没有找到真正的解决方案,但我确实得到了一条建议,这是我选择的路线。由于考虑到多个用户多次上传以在上传时对图像进行调整大小、旋转和其他任何操作的性能,这并不是最佳解决方案,因为这会增加服务器的负担。我们采用的方法是有一个 cdn 服务器,在该服务器上有一个脚本可以检测何时上传新文件并继续进行调整大小和旋转。

我知道这不是对原始问题的实际解决方案,但它是我在考虑性能和优化方面得到的最佳解决方案。

编辑 (12/24/2020): 我不能再推荐这个包,我也不再在我的项目中使用它。这个包缺少 multerS3 的许多其他功能,包括 AUTO_CONTENT_TYPE 我经常使用它来自动设置 S3 中的内容类型。 我强烈建议只坚持使用 multerS3 或者根本不使用 multerS3 并使用 multiparty.

之类的东西自己处理多部分表单数据

原文post: 我在 npm 上找到了这个名为 multer-sharp-s3 Link: https://www.npmjs.com/package/multer-sharp-s3.

的包

我正在使用这个实现:

var upload = multer({
    storage: multerS3({
        s3: s3,
        ACL: 'public-read',
        Bucket: s3Bucket,
        Key: (req, file, cb) => {
            cb(null, file.originalname);
        },
        resize: {
            width: 100,
            height: 100
        }
    }),
    fileFilter: fileFilter
});

希望对您有所帮助!

我尝试了很多不同的支持 Sharp 的 multer-s3 包,但是 none 对我有用,所以我决定使用 multeraws-sdksharp.

这是一个有效的 Express.js 示例。

const path = require('path')
const sharp = require('sharp')
const AWS = require('aws-sdk')
const multer = require('multer')
const express = require('express')
require('dotenv').config({ path: path.join(__dirname, '.env') })

const { AWS_BUCKET, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ENDPOINT } = process.env

const app = express()
const port = 9000

app.use(express.json())
app.listen(port, () => {
  console.log('Example app listening on port http://localhost:' + port)
})

app.get('/', (req, res) => {
  res.send(`
<form action='/upload' method='post' enctype='multipart/form-data'>
  <input type='file' name='file' multiple />
  <input type='submit' value='upload' />
</form>
  `)
})

const sharpify = async originalFile => {
  try {
    const image = sharp(originalFile.buffer)
    const meta = await image.metadata()
    const { format } = meta
    const config = {
      jpeg: { quality: 80 },
      webp: { quality: 80 },
      png: { quality: 80 }
    }
    const newFile = await image[format](config[format])
      .resize({ width: 1000, withoutEnlargement: true })
    return newFile
  } catch (err) {
    throw new Error(err)
  }
}

const uploadToAWS = props => {
  return new Promise((resolve, reject) => {
    const s3 = new AWS.S3({
      accessKeyId: AWS_ACCESS_KEY_ID,
      secretAccessKey: AWS_SECRET_ACCESS_KEY,
      endpoint: new AWS.Endpoint(AWS_ENDPOINT)
    })
    s3.upload(props, (err, data) => {
      if (err) reject(err)
      resolve(data)
    })
  })
}

app.post('/upload', multer().fields([{ name: 'file' }]), async (req, res) => {
  try {
    const files = req.files.file
    for (const key in files) {
      const originalFile = files[key]

      const newFile = await sharpify(originalFile)

      await uploadToAWS({
        Body: newFile,
        ACL: 'public-read',
        Bucket: AWS_BUCKET,
        ContentType: originalFile.mimetype,
        Key: `directory/${originalFile.originalname}`
      })
    }

    res.json({ success: true })
  } catch (err) {
    res.json({ success: false, error: err.message })
  }
})