vue+express实现多文件上传

演示效果

前端代码

<template>
	<div>
		<div>
			<p>
				文件1:<input type="file" @change="fileSelect($event)" />
			p>
			<p>
				文件2:<input type="file" @change="fileSelect($event)" />
			p>
			<p>
				文件3:<input type="file" @change="fileSelect($event)" />
			p>
			<button @click="fileSubmit">上传button>
		div>
		<div class="progress-wrap">
			<p>上传进度p>
			<p class="progress"><span :style="style">span>p>
		div>
	div>
template>

<script>
export default {
	data(){
		return {
			file: [], //上传的文件对象
			progressBar: 0 // 记录上传进度的变量
		}
	},
	computed:{
		style(){ // 进度条样式
			return {
				width: this.progressBar+"%"
			}
		}
	},
	methods:{
		fileSelect(e){ 
			this.file.push(e.target.files[0])
		},
		async fileSubmit(){
			const formData = new FormData();
			this.file.map(f=>{
				formData.append('file',f);
			})
			await this.$axios.post('http://localhost:3000/file/upload',formData,{
				onUploadProgress: (progressEvent)=>{
				 var percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
				 this.progressBar = percentCompleted
			}}).then(res=>{
				console.log(res.data)
			})
		}
	}
}
script>

<style>
.progress-wrap {
	width: 300px;
}
.progress-wrap p {
	width: 100%;
}
.progress {
	background-color: #c5c8ce;
	height: 20px;
}
.progress span {
	display: block;
	background-color: #19be6b;
	height: 100%;
	width: 0;
}
style>

后端代码

let express = require('express')
let router = express.Router()
let multer = require('multer')
let fs = require('fs');
let path = require('path');

let upload = multer({
	storage: multer.diskStorage({
		//设置文件存储位置
		destination: function(req, file, cb) {
			let date = new Date();
			let year = date.getFullYear();
			let month = (date.getMonth() + 1).toString().padStart(2, '0');
			let day = date.getDate();
			let dir = "./uploads/" + year + month + day;

			//判断目录是否存在,没有则创建
			if (!fs.existsSync(dir)) {
				fs.mkdirSync(dir, {
					recursive: true
				});
			}

			//dir就是上传文件存放的目录
			cb(null, dir);
		},
		//设置文件名称
		filename: function(req, file, cb) {
			let fileName = file.fieldname + '-' + Date.now() + path.extname(file.originalname);
			//fileName就是上传文件的文件名
			cb(null, fileName);
		}
	})
});

//array()方法用于处理多个文件上传
//参数一表示,文件上传表单name属性的值
//参数二表示,允许上传文件个数
router.post('/upload', upload.array('file',3), (req, res) => {
	// res.json({
	// 	file: req.file
	// })
	res.json({
		msg: "上传成功"
	})
})

module.exports = router

你可能感兴趣的:(Web全栈案例)