1.环境搭建
前端环境
# 安装Vue脚手架
cnpm i -g @vue/cli
# 创建项目
vue create myapp
# 进入项目目录
cd myapp
# 安装axios
cnpm i axios --save
# 启动项目
npm run serve
后端环境
# 安装express脚手架
cnpm i -g express-generator
# 创建项目
express upload-demo
# 进入项目目录
cd upload-demo
# 安装multer模块
cnpm i multer --save
# 启动项目
npm start
2.核心代码
前端代码
<template>
<div>
<div>
<input type="file" @change="fileSelect($event)" />
<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 {
this.progressBar+"%"
}
}
},
methods:{
fileSelect(e){
this.file = e.target.files[0]
},
async fileSubmit(){
const formData = new FormData();
formData.append('file',this.file);
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 {
300px;
}
.progress-wrap p {
100%;
}
.progress {
background-color: #c5c8ce;
height: 20px;
}
.progress span {
display: block;
background-color: #19be6b;
height: 100%;
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);
}
})
});
router.post('/upload', upload.single('file'), (req, res) => {
res.json({
file: req.file
})
})
module.exports = router
因为要同时在本地启动前端和后端的服务,所以把前端服务端口改成8080
,后端服务端口改成3000
分别启动前端服务和后端服务,在浏览器中访问前端服务地址:http://localhost:8080
效果演示: