首先先看前端Vue,在這里我們使用了elementUI中的upload控件
<el-upload class="upload-demo" drag action="#" multiple :before-upload="beforeUpload"> <i class="el-icon-upload"></i> <div class="el-upload__text">將文件拖到此處,或<em>點擊上傳</em> </div> </el-upload>
其中action里填一個無意義的地址,因為如果使用action中的地址,則url會默認使用Vue項目打開的ip地址及端口號,如http://127.0.0.1:8043/,
此時如果再在action后面填寫http://127.0.0.1:8080/upload,那么完整的請求路徑就會變成http://127.0.0.1:8043/127.0.0.1:8080/excel
解決的辦法就是使用before-upload,然后在方法里指定url
1 beforeUpload(file){ 2 var formdata = new FormData(); 3 formdata.append('file',file); 4 this.$axios.post('http://127.0.0.1:8080/excel',formdata,{ headers : { 'Content-type':'multipart/form-data'}}); 5 },
這里我們使用formdata來保存傳輸文件數據,由於是上傳excel,所以必須在header里更改content-type,否則會報415錯誤
接下來看后台代碼
1 @RequestMapping(value = "/excel",method = RequestMethod.POST) 2 void getAllByExcel(@RequestParam("file") MultipartFile MPfile)
在這里我們使用MultipartFile來接收前端傳來的file,但它與file有些區別,所以我們使用一個函數來將它轉化為file類型,以供后面使用
1 File transfer(MultipartFile file) { 2 if (file != null) { 3 try { 4 String filePath = "C:\\Users\\JAJ5SZH\\IdeaProjects\\Will-Backend\\UploadFile\\"+file.getOriginalFilename(); 5 File savedFile = new File(filePath); 6 boolean isCreateSuccess = savedFile.createNewFile(); 7 // 是否創建文件成功 8 if (isCreateSuccess) { 9 //將文件寫入 10 file.transferTo(savedFile); 11 return savedFile; 12 } 13 } catch (Exception e) { 14 e.printStackTrace(); 15 } 16 } else { 17 System.out.println("文件是空的"); 18 } 19 return null; 20 }
主要使用的是transferTo()這個MultipartFile封裝好的函數,在filePath里面定義我們存放文件的文件夾,文件的命名可以使用uuid
至此,就實現了上傳excel的功能,歡迎指正交流!