springboot+vue實現頁面下載檔案
阿新 • • 發佈:2020-12-23
本文例項為大家分享了springboot+vue頁面下載檔案的具體程式碼,供大家參考,具體內容如下
1.前端程式碼:
<template v-slot:operate="{ row }"> <vxe-button style="color: #409eff; font-weight: bolder" class="el-icon-download" title="成果下載" circle @click="downloadFile(row)"></vxe-button> </template> downloadFile(row) { window.location = "http://localhost:8001/file/downloadFile?taskId=" + row.id; }
2.後端程式碼:
package com.gridknow.analyse.controller; import com.alibaba.fastjson.JSON; import com.gridknow.analyse.entity.DataInfo; import com.gridknow.analyse.service.FileService; import com.gridknow.analyse.utils.Download; import com.gridknow.analyse.utils.Result; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.List; import java.util.Map; /** * @ClassName FileController * @Description: TODO * @Author Administrator * @Date 2020/8/20 14:02 * @Version TODO **/ @Controller @RequestMapping("/file") public class FileController { @Value("${gridknow.mltc.imgurl}") private String imgUrl; @Autowired private FileService fileService; @CrossOrigin @RequestMapping(value = "/upload",method = RequestMethod.POST) @ResponseBody public Result upload(MultipartHttpServletRequest request) { List<MultipartFile> multipartFiles = request.getFiles("file"); Map<String,Object> map = (Map<String,Object>) JSON.parse(request.getParameter("body")); String companyId = request.getParameter("companyId"); String companyName = request.getParameter("companyName"); boolean bool = fileService.uploadAndInsert(multipartFiles,map,companyId,companyName); if (bool) { return new Result(200); } else { return new Result(500); } } @GetMapping("/downloadFile") public ResponseEntity<Object> downloadFile(@RequestParam("taskId") String taskId,HttpServletResponse response) { DataInfo dataInfo = fileService.queryTaskById(taskId); if (dataInfo == null) { return null; } File file = new File(dataInfo.getResponseUrl()); // 檔案下載 if (file.isFile()) { return downloadFile(taskId); } // 資料夾壓縮成zip下載 if (file.isDirectory()) { String parent = file.getParent(); // 建立臨時存放資料夾 File temDir = new File(parent + "/" + taskId); if (!temDir.exists()) { temDir.mkdirs(); } // 將需要下載的資料夾和內容拷貝到臨時資料夾中 try { Download.copyDir(dataInfo.getResponseUrl(),parent + "/" + taskId); } catch (IOException e) { e.printStackTrace(); } // 設定頭部格式 response.setContentType("application/zip"); response.setHeader("Content-Disposition","attachment; filename="+taskId+".zip"); // 呼叫工具類,下載zip壓縮包 try { Download.toZip(temDir.getPath(),response.getOutputStream(),true); } catch (IOException e) { e.printStackTrace(); } // 刪除臨時資料夾和內容 Download.delAllFile(new File(parent + "/" + taskId)); } return null; } public ResponseEntity<Object> downloadFile(String taskId) { DataInfo dataInfo = fileService.queryTaskById(taskId); if (dataInfo == null) { return null; } File file = new File(dataInfo.getResponseUrl()); String fileName = file.getName(); InputStreamResource resource = null; try { resource = new InputStreamResource(new FileInputStream(file)); } catch (Exception e) { e.printStackTrace(); } HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition",String.format("attachment;filename=\"%s",fileName)); headers.add("Cache-Control","no-cache,no-store,must-revalidate"); headers.add("Pragma","no-cache"); headers.add("Expires","0"); ResponseEntity<Object> responseEntity = ResponseEntity.ok() .headers(headers) .contentLength(file.length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(resource); return responseEntity; } }
工具類
package com.gridknow.analyse.utils; import lombok.extern.slf4j.Slf4j; import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * @ClassName Download * @Description: TODO * @Author Administrator * @Date 2020/9/2 9:54 * @Version TODO **/ @Slf4j public class Download { private static final int BUFFER_SIZE = 2 * 1024; public static void toZip(String srcDir,OutputStream out,boolean KeepDirStructure) throws RuntimeException { long start = System.currentTimeMillis(); ZipOutputStream zos = null; try { zos = new ZipOutputStream(out); File sourceFile = new File(srcDir); compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure); long end = System.currentTimeMillis(); log.info("壓縮完成,耗時:" + (end - start) + " ms"); } catch (Exception e) { throw new RuntimeException("zip error from ZipUtils",e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 遞迴壓縮方法 * * @param sourceFile 原始檔 * @param zos zip輸出流 * @param name 壓縮後的名稱 * @param KeepDirStructure 是否保留原來的目錄結構,true:保留目錄結構; * false:所有檔案跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名檔案,會壓縮失敗) * @throws Exception * */ private static void compress(File sourceFile,ZipOutputStream zos,String name,boolean KeepDirStructure) throws Exception { byte[] buf = new byte[BUFFER_SIZE]; if (sourceFile.isFile()) { // 向zip輸出流中新增一個zip實體,構造器中name為zip實體的檔案的名字 zos.putNextEntry(new ZipEntry(name)); // copy檔案到zip輸出流中 int len; FileInputStream in = new FileInputStream(sourceFile); while ((len = in.read(buf)) != -1) { zos.write(buf,len); } // Complete the entry zos.closeEntry(); in.close(); } else { File[] listFiles = sourceFile.listFiles(); if (listFiles == null || listFiles.length == 0) { // 需要保留原來的檔案結構時,需要對空資料夾進行處理 if (KeepDirStructure) { // 空資料夾的處理 zos.putNextEntry(new ZipEntry(name + "/")); // 沒有檔案,不需要檔案的copy zos.closeEntry(); } } else { for (File file : listFiles) { // 判斷是否需要保留原來的檔案結構 if (KeepDirStructure) { // 注意:file.getName()前面需要帶上父資料夾的名字加一斜槓,// 不然最後壓縮包中就不能保留原來的檔案結構,即:所有檔案都跑到壓縮包根目錄下了 compress(file,name + "/" + file.getName(),KeepDirStructure); } else { compress(file,file.getName(),KeepDirStructure); } } } } } /** * 拷貝資料夾 * * @param oldPath 原資料夾 * @param newPath 指定資料夾 */ public static void copyDir(String oldPath,String newPath) throws IOException { File file = new File(oldPath); //檔名稱列表 String[] filePath = file.list(); if (!(new File(newPath)).exists()) { (new File(newPath)).mkdir(); } for (int i = 0; i < filePath.length; i++) { if ((new File(oldPath + File.separator + filePath[i])).isDirectory()) { copyDir(oldPath + File.separator + filePath[i],newPath + File.separator + filePath[i]); } if (new File(oldPath + File.separator + filePath[i]).isFile()) { copyFile(oldPath + File.separator + filePath[i],newPath + File.separator + filePath[i]); } } } /** * 拷貝檔案 * * @param oldPath 資原始檔 * @param newPath 指定檔案 */ public static void copyFile(String oldPath,String newPath) throws IOException { File oldFile = new File(oldPath); File file = new File(newPath); FileInputStream in = new FileInputStream(oldFile); FileOutputStream out = new FileOutputStream(file);; byte[] buffer=new byte[2097152]; while((in.read(buffer)) != -1){ out.write(buffer); } in.close(); out.close(); } /** * 刪除檔案或資料夾 * @param directory */ public static void delAllFile(File directory){ if (!directory.isDirectory()){ directory.delete(); } else{ File [] files = directory.listFiles(); // 空資料夾 if (files.length == 0){ directory.delete(); System.out.println("刪除" + directory.getAbsolutePath()); return; } // 刪除子資料夾和子檔案 for (File file : files){ if (file.isDirectory()){ delAllFile(file); } else { file.delete(); System.out.println("刪除" + file.getAbsolutePath()); } } // 刪除資料夾本身 directory.delete(); System.out.println("刪除" + directory.getAbsolutePath()); } } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。