最近项目中遇到的Ant Design for Vue 上传文件的需求,在期间踩坑无数特此纪录。。。。。。。。
技术栈:
SpringBoot,Ant Design for Vue ,axios
参考官方文档API重写a-upload的文件上传方式,使用axios来进行上传
前端:选择文件后立即上传,前端接受后端成功上传的文件name和UId,并构建一个downloadFiles实例,用于a-upload组件的已上传文件列表回显。
后端:提供一个统一上传接口,上传路径暂定为本地路径,并将文件数据信息写入数据库表中。
话不多说,上代码:
vue 前端代码,Api请参照官方文档
<a-form :form="form">
<a-form-item label="名称" style="margin-bottom: 0;">
<a-input v-decorator="['name', {rules: [{required: true, message: '请输入名称!'}]}]" />
</a-form-item>
<a-form-item>
<a-upload
:multiple="true" // 多文件上传,默认false
:fileList="downloadFiles" // 返回文件列表
:remove="handleDownloadFileRemove" // 删除文件事件
:customRequest="downloadFilesCustomRequest" // 重写上传方法
>
<a-button class="upload-btn"> <a-icon type="upload" > 相关下载 </a-button>
</a-upload>
</a-form-item>
</a-form>
export default {
name: 'demoForm',
data () {
form: this.$form.createForm(this), // 表单数据初始化
downloadFiles: [] // 已经上传的文件列表
},
methods: {
// 重写a-upload的文件上传处理方式
downloadFilesCustomRequest (data) {
this.saveFile(data)
},
// 上传并保存文件
saveFile (data){
const formData = new FormData()
formData.append('file', data.file)
dibootApi.upload('/demo/upload', formData).then((res) => { // 发送http请求
if (res.code === 0){
let file = this.fileFormatter(res.data)
// 上传单个文件后,将该文件会先到a-upload组件的已上传文件列表中的操作
this.downloadFiles.push(file)
} else {
this.$message.error(res.msg)
}
})
},
// 对上传成功返回的数据进行格式化处理,格式化a-upload能显示在已上传列表中的格式(这个格式官方文档有给出的)
fileFormatter(data) {
let file = {
uid: data.uuid, // 文件唯一标识,建议设置为负数,防止和内部产生的 id 冲突
name: data.name, // 文件名
status: 'done', // 状态有:uploading done error removed
response: '{"status": "success"}', // 服务端响应内容
}
return file
},
// 没错,删除某个已上传的文件的时候,就是调用的这里
handleDownloadFileRemove (file) {
const index = this.downloadFiles.indexOf(file)
const newFileList = this.downloadFiles.slice()
newFileList.splice(index, 1)
this.downloadFiles = newFileList
}
}
Spring Boot Java后端
Controller
@PostMapping("/upload")
public ResultUtils (@RequestParam("file") MultipartFile file) throws Exception {
String fileName = file.getOriginalFilename();
String uuuid = UUID.randomUUID().toString();
String paths = "E:/file-path"; // 此处替换要上传的文件地址
File f = new File(paths + uuuid +fileName ); // 此处路径地址需要转义,/改为//,文件名称相同,前一个文件会被替换掉。
file.transferTo(f); // 上传文件
// 保存上传文件SQL
Map<String, Object> map = new HashMap<>();
map.put("paths", filePath);
map.put("fileName", fileName);
//返回页面相应数据
Map<String, Object> resultMap= new HashMap<>();
resultMap.put("uuid", uuid);
resultMap.put("name", name);
return ResultUtils.ok().put("resultMap", resultMap);
}