前端代码
<Upload
ref="upload"
type="drag"
multiple
:show-upload-list="true"
:before-upload="handleUpload"
:data="uploadFile"
:on-success="uploadSuccess"
action="/api/company/upload">
选择文件:<Button icon="ios-cloud-upload-outline">选择上传文件</Button>
</Upload>
- type: drag支持拖拽
- action对应请求url
export default {
data () {
return {
file: [],
uploadFile: []
}
},
created: function () {
},
methods: {
importExcel (url) {
// 清除上次上传记录
this.$refs.upload.clearFiles()
this.file = []
this.uploadFile = []
},
uploadSuccess (response, file, fileList) {
console.log(response)
},
clear () {
// 清除上次上传记录
this.$refs.upload.clearFiles()
},
handleUpload (file) {
// 上传文件前的事件钩子
// 选择文件后 这里判断文件类型 保存文件 自定义一个keyid 值 方便后面删除操作
let keyID = Math.random().toString().substr(2)
file['keyID'] = keyID
// 保存文件到总展示文件数据里
this.file.push(file)
// 保存文件到需要上传的文件数组里
this.uploadFile.push(file)
},
upload () { // 上传文件
for (let i = 0; i < this.uploadFile.length; i++) {
let item = this.file[i]
this.$refs.upload.post(item)
}
}
}
}
设置接口代理,支持跨域,设置完之后需要重新执行 npm run dev
proxyTable: {
'/api': {
target: 'http://localhost:9097', //目标接口域名
changeOrigin: true, //是否跨域
pathRewrite: {
'^/api': '/api' //重写接口
}
}
},
后端代码
@RestController
@RequestMapping("/api/company")
public class CompanyController {
@RequestMapping("/upload")
public String singleFileUpload(MultipartFile file) throws Exception {
System.out.println("成功上传");
return result;
}
}