JAVA代码实现下载单个文件,和下载打包文件

news/2024/7/5 2:47:33

   

//下载单个文件调用方法

/**
    * response
    * imgPath 下载图片地址
    * fileName 保存下载文件名称
    * @date 2015年4月14日 下午5:53:24
    */
    public static void download(HttpServletResponse response,String imgPath,String fileName){
         OutputStream out=null;
         BufferedInputStream br =null;
         try {
                // 设置响应类型为下载
                 response.setContentType("application/x-msdownload;charset=UTF-8");
                 //页面乱码问题
                response.setCharacterEncoding("UTF-8");
                //设置下载文件名称
                response.setHeader("Content-Disposition", "attachment; filename="+fileName);
                //输入流
                br = new BufferedInputStream(new FileInputStream(imgPath));
                byte[] buf = new byte[1024];
                int len = 0;
                out = response.getOutputStream();
                while ((len = br.read(buf)) > 0){
                      out.write(buf, 0, len);
                      out.flush();
                }
                if(null!=out) out.close();
                if(null!=br) br.close();
         } catch (Exception e) {
               e.printStackTrace();
         }
    }

 

 

//下载打包压缩文件调用方法

/**
     *files 需要下载问价的File 集合
    * @Description: TODO(文件打包下载)
    */
    public static HttpServletResponse downLoadFiles(List<File> files,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            ServletContext context=request.getSession().getServletContext();
            /**这个集合就是你想要打包的所有文件,
             * 这里假设已经准备好了所要打包的文件*/
            //List<File> files = new ArrayList<File>();
    
            /**创建一个临时压缩文件,
             * 我们会把文件流全部注入到这个文件中
             * 这里的文件你可以自定义是.rar还是.zip*/

            File file = new File(context.getRealPath("/test.rar"));
            if (!file.exists()){
                file.createNewFile(); 
            }
            response.reset();
            //response.getWriter()
            //创建文件输出流
            FileOutputStream fous = new FileOutputStream(file);  
            /**打包的方法我们会用到ZipOutputStream这样一个输出流,
             * 所以这里我们把输出流转换一下*/
           ZipOutputStream zipOut = new ZipOutputStream(fous);
            /**这个方法接受的就是一个所要打包文件的集合,
             * 还有一个ZipOutputStream*/
            zipFile(files, zipOut);
            zipOut.close();
            fous.close();
            return downloadZip(file,response);
        }catch (Exception e) {
                e.printStackTrace();
            }
        return response ;
    }

 

 /**
     * 把接受的全部文件打成压缩包
     * @param List<File>;
     * @param org.apache.tools.zip.ZipOutputStream
     */
    public static 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 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");
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        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 File
     * @param org.apache.tools.zip.ZipOutputStream
     */
    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, 512);
                    //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();
        }
    }

 

转载于:https://www.cnblogs.com/laotan/p/4546010.html


http://lihuaxi.xjx100.cn/news/272069.html

相关文章

DreamWeaver做ASP 第13页

第七步&#xff1a;修改资料篇 修改资料&#xff01;首先要清醒一点&#xff0c;什么人才可以修改。 一&#xff0c;本人只能修改自己的&#xff1b;二&#xff0c;管理员可以修改所有人的。 那今天先来搞个可以修改自己资料的页面。 顺序是&#xff1a;先确认是正确登录&#…

pytorch .item_pytorch + SGD

梯度下降是模型优化常用方法&#xff0c;原理也比较简单&#xff0c;简言之就是参数沿负梯度方向更新&#xff0c;参数更新公式如下。&#xff0c;其中 表示的是步长&#xff0c;用于控制每次更新移动的步伐。我们将使用pytorch来试验下这个方法。首先先生成模拟数据。x1 目标模…

Java学习提升体系结构

2019独角兽企业重金招聘Python工程师标准>>> 第一步&#xff1a;源码分析 看看大牛是如何写代码的&#xff0c;提升技术审美&#xff0c;提升核心竞争力。&#xff08;重点&#xff09; 第二步&#xff1a;工程化 工欲善其事必先利其器&#xff0c;不管是小白&#…

谈CVPR 2021审稿

点击上方“视学算法”&#xff0c;选择加"星标"或“置顶”重磅干货&#xff0c;第一时间送达作者丨欧阳万里知乎来源丨https://zhuanlan.zhihu.com/p/348428483编辑丨极市平台本文仅供学术参考&#xff0c;如若侵权请联系后台做删文处理本文有感于本次CVPR结果出来后…

你见过最差的算法工程师都有哪些表现?

点击上方“小白学视觉”&#xff0c;选择加"星标"或“置顶”重磅干货&#xff0c;第一时间送达导读&#xff1a;你见过最差的算法工程师什么样&#xff1f;"百度百科型选手&#xff1f;"、"播客型选手&#xff1f;"、"Github型选手"、…

《评人工智能如何走向新阶段》后记(再续20)

320.开源的C跨平台人脸检测项目&#xff0c;仅用CPU就能跑出惊人的1000FPS 在电脑或手机上都可运行&#xff01; 人脸检测广泛用于人机交互、安防监控、社交娱乐等领域。在很多人脸检测方法中&#xff0c;使用卷积神经网络深度算法是目前较为流行的方法之一&#xff0c;然而在…

总在说SpringBoot内置了tomcat启动,那它的原理你说的清楚吗?

点击上方“方志朋”&#xff0c;选择“设为星标”回复”666“获取新整理的面试文章作者&#xff1a;歪头儿在帝都cnblogs.com/sword-successful/p/11383723.html前言 不得不说SpringBoot的开发者是在为大众程序猿谋福利&#xff0c;把大家都惯成了懒汉&#xff0c;xml不配置了&…

io python 读取pdf_实用又好用,6 款 Python 特殊文本格式处理库推荐

以下是一些 Python 编写的用来解析和操作特殊文本格式的库&#xff0c;希望对大家有所帮助。01.Tablibhttps://www.oschina.net/p/TablibTablib 是一个用来处理与表格格式数据有关的 Python 库&#xff0c;允许导入、导出、管理表格格式数据&#xff0c;并具备包括切片、动态列…