前端:
<input type="file" name="file" @change="changeFile" ref="file">
<el-button @click="submit">提交</el-button>
<!------------------------------------------------------------>
<script>
export default{
data(){
return{
file:''
}
},
methods:{
async submit(){
if(this.file=='')
this.$message.warning('请上传文件');
else{
const formData = new FormData();
formData.append('file',this.file);
await this.$axios.post('http://localhost:3000/upload',formData)
.then(()=>{this.$message.success('上传成功')})
.catch(()=>{this.$message.error('上传失败')});
}
},
changeFile(){
this.file=this.$refs.file.files[0];
}
}
}
</script>
后端nodejs 需要用到express框架和multer模块
const express = require('express');
const multer = require('multer');
var app = express();
//存放文件的文件夹路径,不存在会自动创建
const upload = multer({dest:'../upload'});
app.post('/upload',upload.single('file'),(req,res)=>{
res.send();
})
app.listen(3000);
此处因为同源策略,需要跨域
跨域方法请看https://blog.csdn.net/lyy18719172450/article/details/115255806?spm=1001.2014.3001.5501
上传成功会在目录下创建一个文件夹
至此上传功能已经完成,但是文件还是个二进制的文件,详细解决请看https://segmentfault.com/a/1190000020467289?utm_source=tag-newest