gpt4 book ai didi

node.js - 如何在 multer 中捕获错误

转载 作者:行者123 更新时间:2023-12-05 00:47:02 25 4
gpt4 key购买 nike

我已阅读 multer 的文档。但是我在代码中的当前设置是不同的,这让我很难理解如何处理错误。现在很重要,因为它发生(仅一次)文件未存储在服务器上,但代码继续将信息保存在数据库中,就好像文件的存储已经工作一样。但它可能没有。

const multer = require('multer');

var docPath = "path_to_disk_where_to_store_files";

var storage = multer.diskStorage({
inMemory: true,
destination: function (request, file, callback) {
callback(null, docPath);
},
filename: function (request, file, callback) {
//Just a function that creates an unique name with timestamp
renamedFile = helpers.createUniqueName(file.originalname);
callback(null, renamedFile);
}
});

var fileFilter = function (req, file, cb) {
var path = require('path');
var ext = path.extname(file.originalname);
if (file.mimetype !== 'application/pdf' || ext.toLowerCase() != '.pdf') {
req.fileValidationError = 'goes wrong on the mimetype';
return cb(null, false, new Error('goes wrong on the mimetype'));
}
cb(null, true);
};

const multerUploader = multer({storage: storage, fileFilter: fileFilter, limits: { fileSize: maxSize }});

router.post('/save_document',[multerUploader.single('file'),saveDocumentInDb]);

我真的不明白用于检查上传是否出错的 if 语句的位置。

最佳答案

使用multer时的错误处理请引用以下内容: https://github.com/expressjs/multer#error-handling

您的实现将是这样的:

const multerUploader = multer({storage: storage, fileFilter: fileFilter, limits: { fileSize: maxSize }});
const upload = multerUploader.single('file');
router.post('/save_document', function (req, res) {
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
// A Multer error occurred when uploading.
} else if (err) {
// An unknown error occurred when uploading.
}

// Everything went fine and save document in DB here.
})
})

关于node.js - 如何在 multer 中捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59173411/

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