vue中使用elmentUI的Upload组件提交文件和后台接收

1.参考此博客,希望有以下知识储备

vue的路由,跨域请求,springboot2.X,html,已经阅读elementUI官网中关于upload组件的详细介绍。

2.废话不多说,直接讲解细节。前台使用webstorm搭建的vue工程,后台用的idea写的控制层

前台:我是直接copy   elementUI官网的样例,我放在了新建的Upload.vue文件中

==============================================================================================================================
<template>
<div>
<el-upload
class="upload-demo"
ref="upload"
action="/data/upload"
:on-change="changeMe"
name="file"
multiple
:on-preview="handlePreview"
:on-remove="handleRemove"
:file-list="fileList"
:auto-upload="false">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</div>
</template>

<script>
export default {
name: "Upload",
data() {
return {
fileList: []
};
},
methods: {
submitUpload(event) {
event.preventDefault();
this.$refs.upload.submit();
},
changeMe(file,fileList){
this.fileList=fileList;
},
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePreview(file) {
console.log(file);
}
}
}
</script>

<style scoped>

</style>
======================================================================================================================
action="/data/upload" 根据自己后台实际RequestMapping书写,之所以我不写全,是因为下面那个图片,请求地址会自动补全为http://localhost:8080/data/upload
:on-change="changeMe" 这个不用管,是我自己做的测试
name="file" 名字任意,为了后台数据的接收

配置前端路由,如何请求后台

 后端代码如下:

这样就可以接收到前台传来的文件了。如果报

Spring Boot:The field file exceeds its maximum permitted size of 1048576 bytes.

可以参考https://blog.csdn.net/u010429286/article/details/54381705

正常如果能上传就会看到调试窗口的这个内容

很多网上使用设置headers为mutipart/form-data,在此我重申一下,没有必要。elementUI已经封装加工过了。比用再多此一举去设置。

你如果设置了,你会报错boundry什么,我忘记了。所以说不用去设置。

 

猜你喜欢

转载自www.cnblogs.com/fanjunhui/p/11307837.html