Vue 前端
- 將上傳按鈕做成一個 Vue 組件 upload-btn.vue。
具體做法是:在 src/components 目錄下新建一個 公共組件 UploadBtn矗钟,代碼如下:
<template>
<el-button
v-bind="$attrs"
@click="handleUpload">
<slot />
<input
type="file"
ref="file"
:accept="accept"
style="visibility: hidden; width: 1px; height: 1px; vertical-align: middle;"
@change="handleFile"
>
</el-button>
</template>
<script>
export default {
props: {
accept: {type: String}
},
methods: {
handleUpload () {
this.$refs.file.click()
},
handleFile (e) {
const file = e.target.files[0] // 獲得文件對象
e.target.value = '' // 重置 input 的 value锦亦,否則下次選擇同一個文件時(shí)不會觸發(fā) change 事件宇弛。
// do upload
// 為了組件的通用曙痘,本組件不負(fù)責(zé)上傳阳准,交由上層處理
this.$emit('upload', file)
}
}
}
</script>
- 頁面調(diào)用該組件上傳文件
Step1:插入觸發(fā)按鈕
<upload-btn
size="small"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
@upload="handleUpload"
>批量上傳</upload-btn>
Step2:引用組件氛堕,指定上傳方法
import UploadBtn from '@/components/UploadBtn'
export default {
components: {
UploadBtn
},
methods: {
handleUpload (file) {
// https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/append
const form = new FormData();
form.append("file", file, file.name);
// 如果在上傳文件的同時(shí),還要提交更多的信息野蝇,就像下面這樣寫
// form.append("key1", "value");
// 設(shè)置文件上傳的請示頭
//const requestConfig = {
// headers: {
// 'Content-Type': 'multipart/form-data'
// }
// };
// 使用 axios 上傳文件
uploadFile( form).then(resp => {
this.$notify.success(resp.msg)
this.fetchBrandList()
});
}
}
}
這里對 axios 做了封裝讼稚,可以直接調(diào)用 api 中對應(yīng)的方法:
import request from '@/utils/request'
export function uploadFile(data) {
return request({
method: 'post',
url: '/mobile/brand/uploadFile',
data,
headers: {
'Content-Type': 'multipart/form-data'
}
})
}
SpringBoot 后端
Controller 層接收請求:
@RestController
@RequestMapping("/mobile")
public class MobileFilterController {
@Autowired
private MobileBrandService mobileBrandService;
@PostMapping("/brand/uploadFile")
public Response uploadFile(MultipartFile file) throws IOException {
// 解析上傳的 Excel 文件
Response<List<MobileBrandManagement>> response = mobileBrandService.getExcelData(file);
if (!response.isSuccess()) {
return response;
}
List<MobileBrandManagement> list = response.getData();
if (list == null || CollectionUtils.isEmpty(list)) {
return Response.error("上傳文件中無數(shù)據(jù)需要處理");
}
mobileBrandService.addBatch(list);
return Response.success("批量添加成功");
}
}
Service 層處理 Excel 文件,取出數(shù)據(jù)做相應(yīng)的業(yè)務(wù)處理浪耘。
到此乱灵,Vue 上傳文件到后端完成,效果如下:
image.png