vue+axios+elementUI文件上傳與下載

vue+axios+elementUI文件上傳與下載

96 
Simple_Learn 
 0.5 2018.05.30 10:20 字數 209 閱讀 15111評論 4

1.文件上傳javascript

這裏主要介紹一種,elementUI官網 上傳組件 http-request 這種屬性的使用。前端

 
圖片.png

 

代碼以下:vue

<el-upload class="uploadfile" action="" :http-request='uploadFileMethod' :show-file-list="false" multiple> <el-button class="custom-btn" size="small">上傳</el-button> </el-upload> 

uploadFileMethod方法以下:java

uploadFileMethod(param) {
            const id = this.currentRowObject.id; let fileObject = param.file; let formData = new FormData(); formData.append("file", fileObject); this.$store .dispatch("UploadFile", { formData: formData, id: id }) .then(response => { if (Array.isArray(response)) { if (response) { this.$message({ showClose: true, message: "上傳成功。", type: "success" }); this.getFileList(id); } } else { this.$message.error(response.message); } console.log("response==", response); }) .catch(message => { console.log("message======================", message); this.$message.error("上傳失敗,請聯繫管理員"); }); }, 

這裏須要設置header屬性ios


 
api文件

這裏是由於封裝了axios方法,還使用了vuex。git


 
vuex中文件

可將ajax直接替換成axios就好,具體可參見{axios}以下:github

axios.post('/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) 

這裏formData就是要向後臺傳的數據。ajax

2.文件下載vuex

2.1 一種是url式的下載,至關於get請求下載
後臺提供一個url。前端a標籤href設置上就好。axios

//帶文件名的單個文件下載 @RequestMapping(path = "/downloadwithname/{id}", method = RequestMethod.GET) public void downloadWithFileName(@PathVariable(name = "id") String strId, HttpServletResponse response) { Long id = Utils.stringTransToLong(strId); //設置Content-Disposition String fileName = fileService.getFileName(id); InputStream inputStream = fileService.download(id); OutputStream outputStream = null; try { response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8")); outputStream = response.getOutputStream(); IOUtils.copy(inputStream, outputStream); response.flushBuffer(); } catch (IOException e) { logger.error(e.getMessage(), e); throw new BizBaseException("server error."); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } } 
 
圖片.png

2.2一種是post請求下載 (以流的形式下載文件)

downloadFile() {
            const rowId = this.currentRowObject.id; const rowName = this.currentRowObject.name; let params = { ids: this.checkedFileId, id: rowId }; this.$store .dispatch("DownloadFile", params) .then(res => { if (res) { console.log("download===",res); const content = res.data; const blob = new Blob([content]); const fileName = `${rowName}.zip`; if ("download" in document.createElement("a")) { // 非IE下載 const elink = document.createElement("a"); elink.download = fileName; elink.style.display = "none"; elink.href = URL.createObjectURL(blob); document.body.appendChild(elink); elink.click(); URL.revokeObjectURL(elink.href); // 釋放URL 對象 document.body.removeChild(elink); } else { // IE10+下載 navigator.msSaveBlob(blob, fileName); } } }) .catch(() => { this.$message.error("下載附件失敗,請聯繫管理員"); }); } 
 
api.js

 
vuex

總之以下:

axios.post('/download', data, {responseType:'blob' }) 

後端這裏須要設置header:

response.setContentType("application/octet-stream");

// 以流的形式下載文件 try { InputStream fis = new BufferedInputStream(new FileInputStream(zipFilePath)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); response.reset();// 清空response OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipName, "UTF-8"));// 若是輸出的是中文名的文件,在此處就要用URLEncoder.encode方法進行處理 toClient.write(buffer); toClient.flush(); toClient.close(); } catch (IOException ex) { ex.printStackTrace(); } finally { //刪除臨時壓縮文件 try { File f = new File(zipFilePath); f.delete(); } catch (Exception e) { e.printStackTrace(); } } 

就先簡單介紹這裏,若有問題能夠留言討論學習。

相關文章
相關標籤/搜索