gpt4 book ai didi

node.js - 如何处理multer自定义存储中的错误?

转载 作者:行者123 更新时间:2023-12-03 08:44:36 25 4
gpt4 key购买 nike

我正在使用带有锐利和自定义存储的multer,设置了图像上传并且效果很好,但是我无法正确处理错误。
当我上传例如错误的文件类型或文件太大时,服务器崩溃。

在我的app.js上

const upload = multer({
storage: new customStorage({
destination: function(req, file, cb) {
cb(
null,
path.join(
__dirname,
'/images',
new Date().toISOString().replace(/:/g, '-') +
'-' +
file.originalname.replace(/\s+/g, '-')
)
);
}
}),
limits: { fileSize: 5000000 }
});

在我的customStorage.js上
const fs = require('fs');
const sharp = require('sharp');
const nodePath = require('path');

function getDestination(req, file, cb) {
cb(null, 'images');
}

function customStorage(opts) {
this.getDestination = opts.destination || getDestination;
}

customStorage.prototype._handleFile = function _handleFile(req, file, cb) {
this.getDestination(req, file, function(err, path) {
if (err) return cb(err);//***the problem is here.***

const outStream = fs.createWriteStream(path);
const transform = sharp().resize(200, 200);

file.stream.pipe(transform).pipe(outStream);
outStream.on('error', cb);
outStream.on('finish', function() {
cb(null, {
path: 'images/' + nodePath.basename(path),
size: outStream.bytesWritten
});
});
});
};

customStorage.prototype._removeFile = function _removeFile(req, file, cb) {
fs.unlink(file.path, cb);
};

module.exports = function(opts) {
return new customStorage(opts);
};

当我上传另一个文件时,它说:
Error: Input buffer contains unsupported image format
Emitted 'error' event at:
at sharp.pipeline (/Users/David/nodejs-app/node_modules/sharp/lib/output.js:687:18)

我想用express这样处理错误。
return res.status(422).render('admin/edit-product', {flash message here.} 

这就是我处理其他错误(例如,当字段为空时)的方式。

最佳答案

您可以将错误抛出在Multer自定义存储中(已经通过cb(err)完成),然后将其捕获在中间件中以进行快速表达。

const upload = multer({
storage: new customStorage({
destination: function(req, file, cb) {
cb(
null,
path.join(
__dirname,
'/images',
new Date().toISOString().replace(/:/g, '-') +
'-' +
file.originalname.replace(/\s+/g, '-')
)
);
}
}),
limits: { fileSize: 5000000 }
});

var uploadMiddleware = function(req, res, next){
var handler = upload.single('media'); //use whatever makes sense here
handler(req, res, function(err){
//send error response if Multer threw an error
if(err){
res.status(500).render('admin/edit-product', "flash message here.");
}
//move to the next middleware, or to the route after no error was found
next();
});
}

然后在您的快速 route 使用uploadMiddleware:
app.post('/route/edit', uploadMiddleware, function (req, res) {
//handle request and render normally
});

关于node.js - 如何处理multer自定义存储中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57513859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com