前端
<template>
<div class='upload-file'>
<a-button type='primary' @click='visible=true'>上传文件</a-button>
<a-modal v-model='visible'
:width='800'
:confirmLoading='confirmLoading'
title='上传文件' @ok='handleOk'>
<a-upload-dragger
name='file'
:multiple='true'
:before-upload='beforeUpload'
>
<p class='ant-upload-drag-icon'>
<a-icon type='inbox' />
</p>
<p class='ant-upload-text'>
单击或拖动文件到此区域以上载
</p>
<p class='ant-upload-hint'>
支持单次或批量上传。
</p>
</a-upload-dragger>
</a-modal>
</div>
</template>
<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '../../store/mutation-types'
import { postAction } from '../../api/manage'
export default {
name: 'UploadFile',
data() {
return {
visible: false,
url: window._CONFIG['domianURL'] + '/file/uploadBatch',
fileList: [],
confirmLoading: false
}
},
created() {
const token = Vue.ls.get(ACCESS_TOKEN)
this.headers = { 'X-Access-Token': token }
},
methods: {
beforeUpload(file) {
this.fileList = [...this.fileList, file]
return false
},
async handleOk() {
this.confirmLoading = true
let formData = new FormData()
for (let item of this.fileList) {
formData.append('files', item)
}
let rs = await postAction(
this.url,
formData
)
console.log(rs)
}
}
}
</script>
<style scoped>
</style>
后端
@PostMapping("uploadBatch")
public Result<?> upload(HttpServletRequest request) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
List<MultipartFile> files = multipartRequest.getFiles("files");
List<SysFileModel> sysFileModels = new ArrayList<>();
for (MultipartFile file : files) {
try {
SysFileModel sysFileModel = fileModelService.saveFile(file.getInputStream(), file.getOriginalFilename());
sysFileModels.add(sysFileModel);
} catch (IOException e) {
log.error(e.getMessage(), e);
return Result.error(e.getMessage());
}
}
return Result.ok(sysFileModels);
}