最近項目中遇到的Ant Design for Vue 上傳文件的需求,在期間踩坑無數特此紀錄。。。。。。。。
技術棧:
SpringBoot,Ant Design for Vue ,axios
參考官方文檔API重寫a-upload的文件上傳方式,使用axios來進行上傳
前端:選擇文件后立即上傳,前端接受后端成功上傳的文件name和UId,并構建一個downloadFiles實例,用于a-upload組件的已上傳文件列表回顯。
后端:提供一個統(tǒng)一上傳接口,上傳路徑暫定為本地路徑,并將文件數據信息寫入數據庫表中。
話不多說,上代碼:
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) => { // 發(fā)送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', // 狀態(tài)有: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);
}