4

我已经能够使用multer-s3库将图像文件上传到 s3,但现在我正在尝试添加Sharp库以调整大小和旋转,但无法弄清楚它需要去哪里或如何去。这是我当前可用于上传的代码:

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
 });

任何帮助将不胜感激 :)

4

3 回答 3

2

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

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

于 2019-11-28T23:15:26.710 回答
2

编辑(2020 年 12 月 24 日): 我不能再推荐这个包,我不再在我的项目中使用它。这个包缺少 multerS3 的许多其他功能,包括AUTO_CONTENT_TYPE我经常使用的在 S3 中自动设置内容类型的功能。我强烈建议只坚持使用 multerS3 或什至根本不使用 multerS3 并自己处理多部分表单数据,例如multiparty.

原始帖子: 我在 npm 上找到了这个名为multer-sharp-s3Link: 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
});

希望这可以帮助!

于 2020-05-29T01:01:48.537 回答
1

我在 Sharp 支持下尝试了许多不同的 multer-s3 包,但没有一个对我有用,所以我决定使用multer,aws-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 })
  }
})
于 2021-11-25T16:46:15.950 回答