springboot单文件下载和多文件压缩zip下载的实现

单文件下载

//下载单个文件
public void downloadFile(HttpServletResponse response){
    String path = "D:\test\ce\1.txt"
    File file = new File(path);
    if(file.exists()){

      String fileName = file.getName();
      response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
      download(response,file);

    }
  }

public void download(HttpServletResponse response,File file){

    FileInputStream fis = null;
    BufferedInputStream bis = null;
    OutputStream os = null;

    try {
      os = response.getOutputStream();
      fis = new FileInputStream(file);
      bis = new BufferedInputStream(fis);
      byte[] buffer = new byte[bis.available()];
      int i = bis.read(buffer);
      while(i != -1){
        os.write(buffer, 0, i);
        i = bis.read(buffer);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    try {
      bis.close();
      fis.close();
      os.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

多文件压缩下载

//多个文件,压缩成zip后下载
public void downloadMoreFile(HttpServletResponse response) {

    String test1= "D:\test\ce\1.txt";
    String test2= "D:\test\ce\2.txt";

    File tfile= new File(test1);
    File cfile= new File(test2);

    List<File> files = new ArrayList<>();
    files.add(tfile);
    files.add(cfile);
    if (tfile.exists() && cfile.exists()) {

      String zipTmp = "D:\test\ce\1.zip";
      zipd(zipTmp,files,response);

    }
  }

public void zipd(String zipTmp,List<File> files,HttpServletResponse response){
    File zipTmpFile = new File(zipTmp);
    try {
      if (zipTmpFile.exists()) {
        zipTmpFile.delete();
      }
      zipTmpFile.createNewFile();

      response.reset();
      // 创建文件输出流
      FileOutputStream fous = new FileOutputStream(zipTmpFile);
      ZipOutputStream zipOut = new ZipOutputStream(fous);
      zipFile(files, zipOut);
      zipOut.close();
      fous.close();
      downloadZip(zipTmpFile, response);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  //files打成压缩包
  public void zipFile(List files, ZipOutputStream outputStream) {
    int size = files.size();
    for (int i = 0; i < size; i++) {
      File file = (File) files.get(i);
      zipFile(file, outputStream);
    }
  }

  public void zipFile(File inputFile, ZipOutputStream ouputStream) {
    try {
      if (inputFile.exists()) {
        if (inputFile.isFile()) {
          FileInputStream IN = new FileInputStream(inputFile);
          BufferedInputStream bins = new BufferedInputStream(IN, 512);
          ZipEntry entry = new ZipEntry(inputFile.getName());
          ouputStream.putNextEntry(entry);

          int nNumber;
          byte[] buffer = new byte[512];
          while ((nNumber = bins.read(buffer)) != -1) {
            ouputStream.write(buffer, 0, nNumber);
          }

          bins.close();
          IN.close();
        } else {
          try {
            File[] files = inputFile.listFiles();
            for (int i = 0; i < files.length; i++) {
              zipFile(files[i], ouputStream);
            }
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

public static HttpServletResponse downloadZip(File file, HttpServletResponse response) {
    if (file.exists() == false) {
      System.out.println("待压缩的文件目录:" + file + "不存在.");
    } else {
      try {
        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();

        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");

        // 如果输出的是中文名的文件,在此处就要用URLEncoder.encode方法进行处理
        response.setHeader("Content-Disposition",
            "attachment;filename=" + new String(file.getName().getBytes("GB2312"), "ISO8859-1"));
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
      } catch (Exception ex) {
        ex.printStackTrace();
      } finally {
        try {
          File f = new File(file.getPath());
          f.delete();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    return response;
  }

到此这篇关于springboot单文件下载和多文件压缩zip下载的实现的文章就介绍到这了,更多相关springboot文件压缩下载内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 详解SpringBoot下文件上传与下载的实现

    SpringBoot后台如何实现文件上传下载? 最近做的一个项目涉及到文件上传与下载.前端上传采用百度webUploader插件.有关该插件的使用方法还在研究中,日后整理再记录.本文主要介绍SpringBoot后台对文件上传与下载的处理. 单文件上传 / 单文件上传 @RequestMapping(value = "/upload") @ResponseBody public String upload(@RequestParam("file") Multipart

  • 详解SpringBoot文件上传下载和多文件上传(图文)

    最近在学习SpringBoot,以下是最近学习整理的实现文件上传下载的Java代码: 1.开发环境: IDEA15+ Maven+JDK1.8 2.新建一个maven工程: 3.工程框架 4.pom.xml文件依赖项 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation

  • SpringBoot后台实现文件上传下载

    SpringBoot后台如何实现文件上传下载? 最近做的一个项目涉及到文件上传与下载.前端上传采用百度webUploader插件.有关该插件的使用方法还在研究中,日后整理再记录.本文主要介绍SpringBoot后台对文件上传与下载的处理. 单文件上传 // 单文件上传 @RequestMapping(value = "/upload") @ResponseBody public String upload(@RequestParam("file") Multipar

  • springboot 中文件上传下载实例代码

    Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者. Spring Boot特点 1. 创建独立的Spring应用程序 2. 嵌入的Tomcat,无需部署WAR文件 3. 简化Maven配置 4. 自动配置Spr

  • springboot整合vue实现上传下载文件

    springboot整合vue实现上传下载文件,供大家参考,具体内容如下 环境 springboot 1.5.x 完整代码下载:springboot整合vue实现上传下载 1.上传下载文件api文件 设置上传路径,如例子: private final static String rootPath = System.getProperty("user.home")+File.separator+fileDir+File.separator; api接口: 下载url示例:http://l

  • springboot实现文件上传和下载功能

    spring boot 引入"约定大于配置"的概念,实现自动配置,节约了开发人员的开发成本,并且凭借其微服务架构的方式和较少的配置,一出来就占据大片开发人员的芳心.大部分的配置从开发人员可见变成了相对透明了,要想进一步熟悉还需要关注源码. 1.文件上传(前端页面): <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/lo

  • SpringBoot实现文件上传下载功能小结

    最近做的一个项目涉及到文件上传与下载.前端上传采用百度webUploader插件.有关该插件的使用方法还在研究中,日后整理再记录.本文主要介绍SpringBoot后台对文件上传与下载的处理. 单文件上传 // 单文件上传 @RequestMapping(value = "/upload") @ResponseBody public String upload(@RequestParam("file") MultipartFile file) { try { if (

  • SpringBoot 文件上传和下载的实现源码

    本篇文章介绍SpringBoot的上传和下载功能. 一.创建SpringBoot工程,添加依赖 compile("org.springframework.boot:spring-boot-starter-web") compile("org.springframework.boot:spring-boot-starter-thymeleaf") 工程目录为: Application.java 启动类 package hello; import org.springf

  • springboot单文件下载和多文件压缩zip下载的实现

    单文件下载 //下载单个文件 public void downloadFile(HttpServletResponse response){ String path = "D:\test\ce\1.txt" File file = new File(path); if(file.exists()){ String fileName = file.getName(); response.setHeader("Content-Disposition", "at

  • java文件下载代码实例(单文件下载和多文件打包下载)

    这篇文章主要介绍了java文件下载代码实例(单文件下载和多文件打包下载),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 最近项目有需要写文件下载相关代码,这边提交记录下相关代码模块,写的不太好,后期再优化相关代码,有好的建议,可留言,谢谢. 1)单文件下载 public String oneFileDownload(HttpServletRequest request,HttpServletResponse response){ //针对需求需

  • c# 文件压缩zip或将zip文件解压的方法

    1.必须Dll: ICSharpCode.SharpZipLib.dll.可从Nutget程序包中获取. 2.压缩文件 /// <summary> /// 压缩文件成zip /// </summary> /// <param name="fileZip">压缩成zip文件的绝对路径</param> /// <param name="fileName">被压缩指定文件的名字</param> ///

  • SpringBoot集成SFTP客户端实现文件上传下载实例

    目录 背景 依赖 创建工具类 SFTP链接池化 SFTP链接池的使用 集成到SpringBoot中 配置 java Bean注入 背景 在项目开发中,一般文件存储很少再使用SFTP服务,但是也不排除合作伙伴使用SFTP来存储项目中的文件或者通过SFTP来实现文件数据的交互. 我遇到的项目中,就有银行和保险公司等合作伙伴通过SFTP服务来实现与我们项目的文件数据的交互. 为了能够顺利地完成与友商的SFTP服务的连通,我们需要在自己的项目中实现一套SFTP客户端工具.一般我们会采用Jsch来实现SF

  • php实现对文件压缩简单的方法

    压缩一个文件 我们将一个文件生成一个压缩包. <?php $path = "c:/wamp/www/log.txt"; $filename = "test.zip"; $zip = new ZipArchive(); $zip->open($filename,ZipArchive::CREATE); //打开压缩包 $zip->addFile($path,basename($path)); //向压缩包中添加文件 $zip->close();

  • Java如何实现文件压缩与上传FTP

    目录 Java文件压缩与上传FTP 文件压缩 Ftp下载与上传文件 Java程序FTP上传文件 依赖架包 commons-net-3.4.jar Java文件压缩与上传FTP 文件压缩 1.pom文件引入相关jar <dependency>             <groupId>commons-net</groupId>             <artifactId>commons-net</artifactId>            

  • Laravel 中创建 Zip 压缩文件并提供下载的实现方法

    如果您需要您的用户支持多文件下载的话,最好的办法是创建一个压缩包并提供下载.下面通过本文给大家看下在 Laravel 中的实现. 事实上,这不是关于 Laravel 的,而是和 PHP 的关联更多,我们准备使用从 PHP 5.2 以来就存在的 ZipArchive 类 ,如果要使用,需要确保php.ini 中的 ext-zip 扩展开启. 任务 1: 存储用户的发票文件到 storage/invoices/aaa001.pdf 下面是代码展示: $zip_file = 'invoices.zip

  • java实现文件压缩成zip的工具类

    最近碰到个需要下载zip压缩包的需求,于是我在网上找了下别人写好的zip工具类.但找了好多篇博客,总是发现有bug.因此就自己来写了个工具类. 这个工具类的功能为: (1)可以压缩文件,也可以压缩文件夹 (2)同时支持压缩多级文件夹,工具内部做了递归处理 (3)碰到空的文件夹,也可以压缩 (4)可以选择是否保留原来的目录结构,如果不保留,所有文件跑压缩包根目录去了,且空文件夹直接舍弃.注意:如果不保留文件原来目录结构,在碰到文件名相同的文件时,会压缩失败. (5)代码中提供了2个压缩文件的方法,

  • java 压缩和解压缩Zip、Jar、Gzip文件实例代码

    我们经常会使用WinZIP等压缩软件将文件进行压缩以方便传输.在java里面也提供了将文件进行压缩以减少传输时的数据量的类,可以很方便的将文件压缩成ZIP.JAR.GZIP等形式,GZIP主要是在Linux系统下的压缩文件. 下面主要讲的就是ZIP形式的压缩文件,而JAR.GZIP形式的压缩文件也是类似的用法. ZIP是一种很常见的压缩形式,在java中要实现ZIP的压缩主要用到的是java.util.zip这个包里面的类.主要有ZipFile. ZipOutputStream.ZipInput

  • python压缩文件夹内所有文件为zip文件的方法

    本文实例讲述了python压缩文件夹内所有文件为zip文件的方法.分享给大家供大家参考.具体如下: 用这段代码可以用来打包自己的文件夹为zip,我就用这段代码来备份 import zipfile z = zipfile.ZipFile('my-archive.zip', 'w', zipfile.ZIP_DEFLATED) startdir = "/home/johnf" for dirpath, dirnames, filenames in os.walk(startdir): fo

随机推荐