使用formidable解析上传的文件时报Can't set headers after they are sent错误,求解决
发布于 1 年前 作者 Zuson 1109 次浏览 来自 问答

router.post(’/admin-push-post-featureImg’, function(req, res) { var form = new formidable.IncomingForm(); form.uploadDir = __dirname + ‘/…/tmp’; form.maxFieldsSize = 2000 * 1024; form.on(‘progress’, function(bytesReceived, bytesExpected) { if(bytesReceived > form.maxFieldsSize) { resMessageIndex = 6; // res.status(413); this.emit(‘error’); } }) .on(‘fileBegin’, function(name, file) { if(file.type != “image/png” && file.type != “image/jpeg” && file.type != “image/gif”) { resMessageIndex = 7; // res.status(415); this.emit(‘error’); } }) .on(‘file’, function(name, file) { var extName = “”; switch(file.type) { case “image/png”: extName = “png”; break; case “image/gif”: extName = “gif”; break; default: extName = “jpg”; } var alphabet = “0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTOVWXYZ”; var strLength = 10; var strUnique = ‘’; for(var i = 0; i < strLength; i++){ strUnique += alphabet.charAt(Math.floor(Math.random() * alphabet.length)); } var date = new Date(); var dateDirectory = date.getFullYear() + “-” + (“0” + (date.getMonth() + 1)).slice(-2); var dateDay = (“0” + date.getDate()).slice(-2); var imgPath = __dirname + “/…/public/images/charImg”; if(!fs.existsSync(imgPath + “/” + dateDirectory)) { fs.mkdirSync(imgPath + “/” + dateDirectory); } if(!fs.existsSync(imgPath + “/” + dateDirectory + “/” + dateDay)) { fs.mkdirSync(imgPath + “/” + dateDirectory + “/” + dateDay); } fs.renameSync(file.path, imgPath + “/” + dateDirectory + “/” + dateDay
+ “/” + strUnique + date.getTime() + “.” + extName); var tmps = “/images/charImg” + “/” + dateDirectory + “/” + dateDay + “/” + strUnique + date.getTime() + “.” + extName; return res.send({errCode: 0, errMsg: ‘’, data: tmps}); }) .on(‘error’, function(err) { return res.send({errCode: 500, errMsg: resMessage[resMessageIndex]}); // try{ // res.header(‘Connection’, ‘close’); // return res.send(resMessage[resMessageIndex]); // }catch(e){ // console.log(e); // } }); form.parse(req); });粘贴图片.png

4 回复

把中间件的执行顺序交换一下试试

res.send 不能调用多次, 你的控制流程有问题

回到顶部