前端代码
elupload.vue文件
- 属性action是文件上传的地址,也就是平时我们调用的接口
- el-upload自带了一个submit方法是用来上传文件的
- 如果要自定义submit的话el-upload需要加上:http-request="submit"
<template>
<el-form :model="form">
<el-form-item label="上传文件" :label-width="formLabelWidth">
<el-upload ref="uploadDemo" action="/api/elupload" :auto-upload="false" multiple :file-list="fileList">
<el-button size="small" type="primary">选择文件</el-button>
</el-upload>
</el-form-item>
<el-form-item>
<el-button size="small" type="primary" @click="uploadFile">立即上传</el-button>
<el-button size="small">取消</el-button>
</el-form-item>
</el-form>
</template>
<script>
export default {
data() {
return {
formLabelWidth: '80px',
form: {
file: ''
},
fileList: []
}
},
methods: {
uploadFile() {
this.$refs.uploadDemo.submit()
}
// submit(params) { // 如果要自定义submit的话el-upload需要加上:http-request="submit"
// console.log(params)
// const form = new FormData()
// form.append('xml', params.file)
// this.$http.post('/elupload', form, {
// headers: {
// 'Content-Type': 'multipart/form-data'
// }
// }).then(() => {
// this.$notify({
// title: '成功',
// message: '导入成功',
// type: 'success',
// duration: 2000
// })
// })
// }
}
}
</script>
vue.config.js文件用来代理跨域
- 这个demo的代理路径需要rewrite到根路径'/'
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:7070',
secure: false,
changeOrigin: true,
pathRewrite: {
'^/api': '/'
}
}
}
}
}
后端代码
@RestController
@CrossOrigin
public class ElUpload {
@Value("${filepath}")
public String filePath;
@RequestMapping("/elupload")
public String elUpload(MultipartFile file){
String fileName = file.getOriginalFilename();
File dest = new File(filePath + fileName);
try {
file.transferTo(dest);
return "上传成功";
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败!";
}
}