node.js - Multer 正在返回一个空响应
问题描述
我正在上传一张图片,但是当我尝试实现一个函数时,我可以更改文件名以包含存储后的日期。
使用下面的代码,我将得到一个空对象,但仍然是一条成功的消息。但是如果我在代码中取消注释它会起作用,但它不会包含日期。
const express = require("express");
const multer = require("multer");
const app = express();
const fileFilter = function(req, file, cb){
const allowedTypes = ["image/jpeg","image/png", "image/gif"];
if(!allowedTypes.includes(file.mimetype)) {
const error = new Error("wrong file type");
error.code = "LIMIT_FILE_TYPES";
return cb(error, false);
}
cb(null, true);
}
const storage = multer.diskStorage({
destination:function(req, file, cb){
cb(null, './uploads/')
},
filename:function(req, file, cb){
cb(null, file + '-' + Date.now())
}
});
const MAX_SIZE = 200000
const upload = multer({
// dest: './uploads/', If I un-comment this line it will upload the image but will not change file name will still be random hash numbers
fileFilter,
storage:storage,
limits:{
fileSize: MAX_SIZE
}
});
app.post('/upload', upload.single('file'), (req, res) => {
res.json({file:req.file});
});
app.use(function(err, req, res, next) {
if(err.code === "LIMIT_FILE_TYPES") {
res.status(422).json({error:"Only Images are Allowed"});
return;
}
if (err.code ==="LIMIT_FILE_SIZE"){
res.status(422).json({error:`Size is to Large, Max size is ${MAX_SIZE/
1000}KB`});
return;
}
});
app.listen(3344, () => console.log("running local on 3344"));
解决方案
它返回 undefined ,因为您正在创建一个组合文件对象 + '-' + Date.now() 的字符串,因此更改此行:
cb(null, file + '-' + Date.now())
对此:
cb(null, file.fieldname + '-' + Date.now())
它应该完成这项工作。
推荐阅读
- mysql - 使用两个具有相同限制的表无法获得正确的结果
- php - 使用 htaccess 从一个文件夹重定向到同一域上的另一个文件夹
- tensorflow - 是否可以在 TensorFlow 2.X 中为没有占位符的 Predict SignatureDef 创建一个具有任意多个输入张量的 Estimator?
- perl - Perl 新手初体验 Unicode(在文件名、-e 运算符、打开运算符和 cmd 窗口中)
- java - Gradle Plugin 如何将方法添加到特定块?
- reactjs - React - 更新嵌套状态(类组件)
- excel - 如果是,则查找某些文本..复制同一行的单元格值
- python - 关于使用 jupyter notebook 的 python 中的关键错误
- extjs - Extjs Panel 渲染两次?
- jquery - 未从控制器中的 ajax 调用获取数据----所需的数据参数“数据”不存在