vue+axios+elementUI文件上传与下载
1.文件上传
这里主要介绍一种,elementUI官网 上传组件 http-request 这种属性的使用。

图片.png
代码如下:
<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方法如下:
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属性

api文件
这里是因为封装了axios方法,还使用了vuex。

vuex中文件
可将ajax直接替换成axios就好,具体可参见{axios}如下:
axios.post('/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
这里formData就是要向后台传的数据。
2.文件下载
2.1 一种是url式的下载,相当于get请求下载
后台提供一个url。前端a标签href设置上就好。
//带文件名的单个文件下载 @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(); } }
就先简单介绍这里,如有问题可以留言讨论学习。