![](/img/trans.png)
[英]How to resize image with sharp then upload with multer in nodejs
[英]Multer-S3 with sharp upload and resize
我已经能够使用multer-s3库将图像文件上传到 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
。
原帖:我在 npm 上找到了这个包,名为multer-sharp-s3
链接: https : 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 软件包,但没有一个对我multer
,所以我决定使用multer
, aws-sdk
和sharp
。
这是一个有效的 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: { compressionLevel: 8 }
}
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 })
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.