nodejs文件上傳炒雞清楚版
- 我們需要下載模塊
npm i express body-parser multer --save
- fileFilter 設(shè)置自定義過(guò)濾方法
var fileFilter = function (req, file, cb) {
var acceptableMime = ["image/jpeg", "image/png", "image/jpg", "image/gif"];
// 限制類(lèi)型
// null是固定寫(xiě)法
if (acceptableMime.indexOf(file.mimetype) !== -1) {
cb(null, true); // 通過(guò)上傳
} else {
cb(null, false); // 禁止上傳
}
}
- storage 設(shè)置文件服務(wù)器存放位置及名稱(chēng)
var path = require("path");
var storage = multer.diskStorage({
//設(shè)置 上傳圖片服務(wù)器位置
destination: path.resolve(__dirname, "./upload"),
//設(shè)置 上傳文件保存的文件名
filename: function (req, file, cb) {
// 獲取后綴擴(kuò)展
let extName = file.originalname.slice(file.originalname.lastIndexOf(".")); //.jpg
// 獲取名稱(chēng)
let fileName = Date.now();
console.log(fileName + extName); //12423543465.jpg
cb(null, fileName + extName);
},
});
- limits 設(shè)置限制文件大衅鲎(可選)
var limits = {
fileSize: "2MB", //設(shè)置限制(可選)
}
傳入以上三項(xiàng)配置
//單張上傳
var multer = require("multer");
const imageUploader = multer({
fileFilter,
storage,
limits
}).single("file"); //文件上傳預(yù)定 name 或者 字段
--------------------------------------------------二選一
//多張上傳
var multer = require("multer");
const imageUploader = multer({
fileFilter,
storage,
limits
}).array("file");
//以上三個(gè)字段是固定寫(xiě)法
- node中間使用,注意 express post 需要配置
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())
app.post("/upload", imageUploader, (req, res) => {
res.send("上傳成功");
});
前端配置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.staticfile.org/axios/0.19.2/axios.js"></script>
</head>
<body>
<input type="file" class="file" />
<script>
var oIpt = document.querySelector(".file");
oIpt.addEventListener("change", function (e) {
// console.log(e.target.files[0]);
var file = new FormData();
file.append("file", e.target.files[0]);
axios({
method: "POST",
url: "/upload",
data: file, //傳入數(shù)據(jù)為二進(jìn)制數(shù)據(jù)流
});
});
</script>
</body>
</html>