code first
I use vuejs.'@change'. As far as I know, only Chrome implements folder uploads. webkitdirectory is a must. vuejs
<!--html-->
<input type="file" name="file" id="file" webkitdirectory @change="changeFile($event)">
vue methods
//javascript
function changeFile(event) {
this.Files = event.target.files;
}
function uploadFiles() {
var fd = new FormData();
for (var i = 0; i < this.Files.length; i++) {
fd.append("file", this.Files[i]);
}
this.$http.post(CONST.HOST+"/order/upload/imgs",//upload address
fd,//params
{
'Content-Type': 'multipart/form-data'//'multipart/form-data'
}
).then(function (res) {
res.json().then(function (result) {
that.result = result.info;
console.log(that.result);
});
}, function (res) {
console.log(res.body);
});
}
Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency. Folder uploads and multi-file uploads are the same for the back end. Get the folder path from the file object. multer
//nodejs
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {//save path
const folderExec = new RegExp('^(.*)/([^/]+)$').exec(file.originalname);//get folder path width regexp
let folder = "";
if(folderExec) {
folder = folderExec[1];
util.createFolder(path.resolve(__dirname, '../uploads/' + folderExec[1]));//create folder
//function createFolder(folder){
// const fs = require('fs');
// if(!fs.existsSync(folder)){
// fs.mkdirSync(folder);
// }
}
}
cb(null, path.resolve(__dirname, '../uploads/' + folder));
},
filename: function (req, file, cb) {//save name
const folderExec = new RegExp('^(.*)/([^/]+)$').exec(file.originalname);
let folder = "";
if(folderExec) {
folder = folderExec[2];
}else{
folder = file.originalname;
}
cb(null, folder);
}
})
var upload = multer({
storage: storage,
preservePath: true//save originalname as perservepath. completion path.
}).any();
router.post("/upload/imgs", upload, (req, res, next) => {
OrderDao.uploading(req, res, next);
});