使用NodeJS Multer转换上传 [英] Transform upload with NodeJS Multer
问题描述
我目前正在为我的用户实施文件/图像上传服务.在上传到s3存储桶之前,我想先对这些图像进行转换(调整大小/优化).
I'm currently implementing a file/image upload service for my users. I want to transform these images (resize/optimize) before uploading to my s3 bucket.
我目前正在做什么:在前端使用多部分表单(我认为实际的实现在这里没有关系..),在后端使用multer
和multer-s3
软件包.
What I'm currently doing: Using a multipart form on my frontend (I think the actual implementation doesn't matter here..) and the multer
and multer-s3
packages on my backend.
在这里,我的实现简化为重要部分.
Here my implementation stripped down to the important parts.
// SETUP
var multer = require('multer');
var s3 = require('multer-s3');
var storage = s3({
dirname: 'user/uploads',
bucket: auth.aws.s3.bucket,
secretAccessKey: auth.aws.s3.secretAccessKey,
accessKeyId: auth.aws.s3.accessKeyId,
region: auth.aws.s3.region,
filename: function (req, file, cb) {
cb(null, Date.now());
}
});
var upload = multer({storage: storage}).single('img');
// ROUTE
module.exports = Router()
.post('/', function (req, res, next) {
upload(req, res, function (err) {
if (err) {
return res.status(401).json({err: '...'});
}
return res.json({err:null,url: '..'});
});
});
我要做什么:在上传图像之前先对其进行转换.我不确定是否需要在这里使用multer/busboy,还是可以使用NodeJS来做到这一点(因此,我已经标记了NodeJS并表示出来).
What I want to do: transform the image before uploading it. I'm not sure if I need to use multer/busboy here or I can just do it with NodeJS (thus I've tagged NodeJS and express as well).
所以我的问题是:在将上传到我的S3存储桶之前,我可以在哪里截取上传并对其进行转换?
So my question is: where can I intercept the upload and transform it before uploading it to my S3 bucket?
推荐答案
不确定您是否还在寻找答案,但我遇到了同样的问题.我决定扩展multer-s3
软件包.
Not sure if you're still looking for an answer to this, but I had the same problem. I decided to extend the multer-s3
package.
我已经打开了对原始存储库的提取请求,但是到目前为止,您可以使用我的叉子.
I've opened a pull request to the original repository, but for now, you can use my fork.
以下是使用扩展版本的示例:
Here's an example of how to use the extended version:
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())
}
}]
})
})
编辑:现在,我的叉子也可以通过npm以multer-s3-transform
的名称使用.
My fork is also now available via npm under the name multer-s3-transform
.
这篇关于使用NodeJS Multer转换上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!