multer,是express上传文件的中间件,一般使用multer@0.1.8版本
例:
multer.html
<form action="" method="post" enctype="multipart/form-data" id="musicFile">
<input type="file" class="txtBox" name="musicFile" id="upload" style="margin-left:25%" accept=".mp3,.wav,.wma,.ogg"/>
</form>
注:accept 为指定上传文件的格式
app.js
//依赖安装multer包 npm install multer --save
//引用包 const multer = require("multer");
//配置上传文件 (upload为存入上传的文件夹)
app.use(multer({dest:'./public/upload',rename:function(filedname,filename) {
return filename+"_"+Date.now();
}
})
);
//引用上传文件的路由
const uploadRoute = require("./route/uploadRouter.js");
路由文件 multerRouter.js
musicRoute.route("/musicUpload.do").post(musicControl.musicUpload); //上传数据
业务层 multerController.js
//上传音乐
musicUpload(req,res){
let musicPath =req.files.musicFile.path;
//console.log(musicPath);
res.json({code:200,path:musicPath})
}
multer.js
//上传文件 ajax方法请求
function musicUpload(){
let form = document.getElementById("musicFile");
let formData = new FormData(form);
let httpRequest;
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else {
httpRequest = new ActiveXObject("Microwsoft.XMLHTTP");//ie7以下版本
}
httpRequest.open("post", "/music/musicUpload.do");
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
let data=httpRequest.responseText;
let obj = JSON.parse(data);
resolve(obj)
}
};
httpRequest.send(formData);
}
注:以上是本人在做上传音乐的时候总结,有许多不足之处,还希望大家多多指教。