Multer 已经有限制大小的属性。此属性仅限制图像。不调整图像大小。我的问题是假设图像大于“限制大小”,如何调整该图像的大小?
var storageOptions = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'useravatars/')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
});
var avatarUpload = multer({
storage: storageOptions,
limits: {
fileSize: 1000000
}
}).single("avatar");
Run Code Online (Sandbox Code Playgroud)
这取决于您是否还想存储调整大小的图像。
在任何情况下,您都将使用一个库来处理调整大小操作。锋利是一个非常好的选择。
在路由处理程序中调整大小(在文件存储到磁盘后):
sharp(req.file).resize(200, 200).toBuffer(function(err, buf) {
if (err) return next(err)
// Do whatever you want with `buf`
})Run Code Online (Sandbox Code Playgroud)
其他选项是创建自己的存储引擎,在这种情况下,您将接收文件数据,调整大小,然后存储到磁盘(从https://github.com/expressjs/multer/blob/master/StorageEngine.md复制) :
var fs = require('fs')
function getDestination(req, file, cb) {
cb(null, '/dev/null')
}
function MyCustomStorage(opts) {
this.getDestination = (opts.destination || getDestination)
}
MyCustomStorage.prototype._handleFile = function _handleFile(req, file, cb) {
this.getDestination(req, file, function(err, path) {
if (err) return cb(err)
var outStream = fs.createWriteStream(path)
var resizer = sharp().resize(200, 200).png()
file.stream.pipe(resizer).pipe(outStream)
outStream.on('error', cb)
outStream.on('finish', function() {
cb(null, {
path: path,
size: outStream.bytesWritten
})
})
})
}
MyCustomStorage.prototype._removeFile = function _removeFile(req, file, cb) {
fs.unlink(file.path, cb)
}
module.exports = function(opts) {
return new MyCustomStorage(opts)
}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12128 次 |
| 最近记录: |