java如何实现以数据流的形式下载压缩包到本地?

该博客介绍了一个使用Java Spring MVC实现批量下载文件并打包为RAR压缩包的方法。通过创建一个名为`ManualController`的控制器,提供了一个`downloadManual`的请求映射,它读取E盘下的`manual`文件夹,将所有文件打包成一个RAR文件,然后以流的形式返回给客户端进行下载。代码中包含了文件打包、流处理和响应设置的细节。
摘要由CSDN通过智能技术生成

先不多说,直接贴代码吧,在服务器的E盘下放一个E:/manual.rar的压缩包

package com.cellstrain.icell.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Controller
public class ManualController {
    /**
     * 产品手册批量下载(以压缩包的格式)
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("downloadManual")
    public HttpServletResponse downLoadFiles(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            File dir = new File("E:\\manual\\");
            /**创建一个临时压缩文件,我们会把文件流全部注入到这个文件中,这里的文件你可以自定义是.rar还是.zip**/
            File file = new File("E:/manual.rar");
            if (!file.exists()) {
                file.createNewFile();
            }
            response.reset();
            return downloadZip(file, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        /**直到文件的打包已经成功了,文件的打包过程被我封装在FileUtil.zipFile这个静态方法中,稍后会呈现出来,接下来的就是往客户端写数据了**/
        return response;
    }

    /**
     * 以流的形式下载文件
     *
     * @param file
     * @param response
     * @return
     */
    public static HttpServletResponse downloadZip(File file, HttpServletResponse response) {
        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=" + URLEncoder.encode(file.getName(), "UTF-8"));
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                File f = new File(file.getPath());
//                f.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    /**
     * 根据输入的文件与输出流对文件进行打包
     *
     * @param inputFile
     * @param ouputStream
     */
    public static void zipFile(File inputFile, ZipOutputStream ouputStream) {
        try {
            if (inputFile.exists()) {
                /**如果是目录的话这里是不采取操作的,至于目录的打包正在研究中**/
                if (inputFile.isFile()) {
                    FileInputStream IN = new FileInputStream(inputFile);
                    BufferedInputStream bins = new BufferedInputStream(IN, 1024);
                    //org.apache.tools.zip.ZipEntry
                    ZipEntry entry = new ZipEntry(inputFile.getName());
                    ouputStream.putNextEntry(entry);
                    // 向压缩文件中输出数据
                    int nNumber;
                    byte[] buffer = new byte[1024];
                    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();
        }
    }
}
效果图如下:

 

可以自己手动选择文件的存放位置,pdf、word、excel等类似

原文博客的链接地址:https://www.cnblogs.com/qianzf/p/6780856.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值