前端代码
elupload.vue文件
<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文件用来代理跨域
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 "上传失败!"; } }