- 依赖
Express
Multer
- 通过
Express
构建项目后,在./routes/index.js
中添加代码,添加后如下:
var express = require('express');
var router = express.Router();
var multer = require('multer');
// 配置文件的存储位置
var Storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './public/images');
},
filename: function(req, file, callback) {
callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
}
});
var upload = multer({
storage: Storage
}).single("imgUploader"); // Field name
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
// form action
router.post("/api/upload", function(req, res) {
upload(req, res, function(err) {
if (err) {
console.log(err);
return res.end("Something went wrong!");
}
return res.end("File uploaded successfully!");
});
});
module.exports = router;
- 修改
views/index.jade
后如下:
extends layout
block content
h1= title
p Welcome to #{title}
form(action="/api/upload", method="post", enctype="multipart/form-data")
input(type="file", name="imgUploader", multipart)
input(type="submit", name="submit", value="Upload")
-
运行后界面如下:
截屏2021-02-01 下午4.30.19.png
选择图片上传测试成功即完成
网友评论