我正在制作一个小脚本来上传照片并将其保存到本地存储中。我正在为此使用Express和Muller。
我有一个带有上传字段的html页面(请参见下文)。我一按“上传照片”按钮,他就将照片发送到端点“ / upload”。在这里,只有当帖子“ req.file”为空时,他才应将照片以“ image.jpg”的名称保存在我的计算机上。
我只是想知道怎么回事?我想念什么吗?
App.js
const express = require("express");
const multer = require("multer");
const helpers = require("./helpers");
const app = express();
const port = process.env.PORT || 3000;
app.use(express.static(__dirname + "/"));
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "uploads/");
},
filename: function (req, file, cb) {
cb(null, "image.jpg");
},
});
app.listen(port, () => console.log(`Listening on port ${port}...`));
app.post("/upload", (req, res) => {
let upload = multer({
storage: storage,
fileFilter: helpers.imageFilter,
}).single("image");
upload(req, res, function (err) {
if (req.fileValidationError) {
return res.send(req.fileValidationError);
} else if (!req.file) {
return res.send("Please select an image to upload");
} else if (err instanceof multer.MulterError) {
return res.send(err);
} else if (err) {
return res.send(err);
}
res.send(
`You have uploaded this image: <hr/><img src="${req.file.path}" width="500"><hr /><a href="./">Upload another image</a>`
);
});
});
Helpers.js
const imageFilter = function(req, file, cb) {
// Accept images only
if (!file.originalname.match(/\.(jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF)$/)) {
req.fileValidationError = 'Only image files are allowed!';
return cb(new Error('Only image files are allowed!'), false);
}
cb(null, true);
};
exports.imageFilter = imageFilter;
HTML页面
<form action="/upload" enctype="multipart/form-data" method="POST">
<input type="file" name="image" accept="image/*" />
<input type="submit" value="Upload Photo" />
</form>
答案 0 :(得分:0)
在“常量存储”中出错了。我填写了错误的文件路径。但是奇怪的是req.file是空的...无论如何,它可以工作!