电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

springboot+vue實現頁面下載文件

瀏覽:18日期:2022-10-17 08:31:52

本文實例為大家分享了springboot+vue頁面下載文件的具體代碼,供大家參考,具體內容如下

1.前端代碼:

<template v-slot:operate='{ row }'> <vxe-button 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 **/@Slf4jpublic 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, 0, 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, zos, name + '/' + file.getName(), KeepDirStructure); } else { compress(file, zos, 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()); } }}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Spring
相關文章:
主站蜘蛛池模板: 微水泥_硅藻泥_艺术涂料_艺术漆_艺术漆加盟-青岛泥之韵环保壁材 武汉EPS线条_EPS装饰线条_EPS构件_湖北博欧EPS线条厂家 | 大白菜官网,大白菜winpe,大白菜U盘装系统, u盘启动盘制作工具 | 成都竞价托管_抖音代运营_网站建设_成都SEM外包-成都智网创联网络科技有限公司 | 常州翔天实验仪器厂-恒温振荡器-台式恒温振荡器-微量血液离心机 恒温恒湿箱(药品/保健品/食品/半导体/细菌)-兰贝石(北京)科技有限公司 | 武汉刮刮奖_刮刮卡印刷厂_为企业提供门票印刷_武汉合格证印刷_现金劵代金券印刷制作 - 武汉泽雅印刷有限公司 | 湖州织里童装_女童男童中大童装_款式多尺码全_织里儿童网【官网】-嘉兴嘉乐网络科技有限公司 | 能耗监测系统-节能监测系统-能源管理系统-三水智能化 | 植筋胶-粘钢胶-碳纤维布-碳纤维板-环氧砂浆-加固材料生产厂家-上海巧力建筑科技有限公司 | 小港信息港-鹤壁信息港 鹤壁老百姓便民生活信息网站 | 档案密集架_电动密集架_移动密集架_辽宁档案密集架-盛隆柜业厂家现货批发销售价格公道 | 锯边机,自动锯边机,双面涂胶机-建业顺达机械有限公司 | 微信聊天记录恢复_手机短信删除怎么恢复_通讯录恢复软件下载-快易数据恢复 | 点胶机_点胶阀_自动点胶机_智能点胶机_喷胶机_点胶机厂家【欧力克斯】 | 中空玻璃生产线,玻璃加工设备,全自动封胶线,铝条折弯机,双组份打胶机,丁基胶/卧式/立式全自动涂布机,玻璃设备-山东昌盛数控设备有限公司 | 捆扎机_气动捆扎机_钢带捆扎机-沈阳海鹞气动钢带捆扎机公司 | 河南新乡德诚生产厂家主营震动筛,振动筛设备,筛机,塑料震动筛选机 | 真空干燥烘箱_鼓风干燥箱 _高低温恒温恒湿试验箱_光照二氧化碳恒温培养箱-上海航佩仪器 | 全自动实验室洗瓶机,移液管|培养皿|进样瓶清洗机,清洗剂-广州摩特伟希尔机械设备有限责任公司 | 苏州同创电子有限公司 - 四探针测试仪源头厂家 | 北京浩云律师事务所-企业法律顾问_破产清算等公司法律服务 | 防爆大气采样器-防爆粉尘采样器-金属粉尘及其化合物采样器-首页|盐城银河科技有限公司 | 液压油缸-液压缸厂家价格,液压站系统-山东国立液压制造有限公司 液压油缸生产厂家-山东液压站-济南捷兴液压机电设备有限公司 | 祝融环境-地源热泵多恒系统高新技术企业,舒适生活环境缔造者! | 诺冠气动元件,诺冠电磁阀,海隆防爆阀,norgren气缸-山东锦隆自动化科技有限公司 | 杭州实验室尾气处理_实验台_实验室家具_杭州秋叶实验设备有限公司 | 安徽免检低氮锅炉_合肥燃油锅炉_安徽蒸汽发生器_合肥燃气锅炉-合肥扬诺锅炉有限公司 | 中国产业发展研究网 - 提供行业研究报告 可行性研究报告 投资咨询 市场调研服务 | 撕碎机,撕破机,双轴破碎机-大件垃圾破碎机厂家 | 冷藏车厂家|冷藏车价格|小型冷藏车|散装饲料车厂家|程力专用汽车股份有限公司销售十二分公司 | 铝合金脚手架厂家-专注高空作业平台-深圳腾达安全科技 | 冰晶石|碱性嫩黄闪蒸干燥机-有机垃圾烘干设备-草酸钙盘式干燥机-常州市宝康干燥 | 首页_欧瑞传动官方网站--主营变频器、伺服系统、新能源、软起动器、PLC、HMI | 山东聚盛新型材料有限公司-纳米防腐隔热彩铝板和纳米防腐隔热板以及钛锡板、PVDF氟膜板供应商 | 首页_欧瑞传动官方网站--主营变频器、伺服系统、新能源、软起动器、PLC、HMI | 广州企亚 - 数码直喷、白墨印花、源头厂家、透气无手感方案服务商! | 岸电电源-60HZ变频电源-大功率变频电源-济南诚雅电子科技有限公司 | 真空泵维修保养,普发,阿尔卡特,荏原,卡西亚玛,莱宝,爱德华干式螺杆真空泵维修-东莞比其尔真空机电设备有限公司 | 上海办公室装修,办公楼装修设计,办公空间设计,企业展厅设计_写艺装饰公司 | 武汉印刷厂-不干胶标签印刷厂-武汉不干胶印刷-武汉标签印刷厂-武汉标签制作 - 善进特种标签印刷厂 | Dataforth隔离信号调理模块-信号放大模块-加速度振动传感器-北京康泰电子有限公司 | 球磨机 选矿球磨机 棒磨机 浮选机 分级机 选矿设备厂家 |