我使用此代码" multer"将文件上传到我的服务器。即使我有限制文件大小,也只是忽略它并上传文件。
const multer = require("multer");
const path = require("path");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "uploads/");
},
limits: {
fileSize: 1024 * 1024
}
});
const upload = multer(
{
storage: storage
}
).single("file");
router.post("/files/postfile", function (req: any, res: any, next) {
upload(req, res, function (err) {
if (err) {
return res.json({error: err});
}
return res.json({success: true});
});
});
答案 0 :(得分:2)
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024
}
}).single("file");
从limits
multer.diskStorage
答案 1 :(得分:-1)
您的代码效率很低。
const multer = require("multer");
const path = require("path");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "uploads/");
}
});
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024
}
});
router.post("/files/postfile", upload.single("file"); function (req: any, res: any, next) {
// . . . . code . . . .
});
通过使用中间件,您可以编写有效的代码 我推荐这种方法。 如果在multer.diskStorage()调用时使用filename属性,则可以使用文件名chage。
destination: function (req, file, cb) {
cb(null, "uploads/");
},
filename: function(req, file, cb){
cb(null, 'unique_name.jpg'); # example: timestamp, utc, etc
},
limits: {
fileSize: 1024 * 1024
}
文件名可以复制。