从项目中的文件夹中下载压缩文件

本文介绍了一种在Java中实现从项目文件夹下载指定压缩文件的方法,通过使用FileInputStream和OutputStream进行文件读写,实现了文件的下载功能,并在下载完成后清理了临时文件。

/**
     *前面页面采用a标签,ajax成功后打开页面指定项目中的下载压缩文件的方法
     * window.open(contextPath+"/html/html_downloadZipFile.do?fileName="+encodeURIComponent(id+"/"+fileName));
     * 从项目中的文件夹中下载压缩文件
     * @throws Exception
     */
    public void downloadZipFile() throws Exception{
        String downloadPath = getRequest().getSession().getServletContext()
                .getRealPath("/")+ "download/";
        //获取get方法参数
        ActionContext context = ActionContext.getContext();
        Map<String, Object> parameterMap = context.getParameters();
        String fileNameArray[] = (String[]) parameterMap.get("fileName");
        String fileName = fileNameArray[0];
        //解码
        fileName = java.net.URLDecoder.decode(fileName,"UTF-8");
        //设置编码
        getRequest().setCharacterEncoding("UTF-8");
        //指定需要下载压缩包的名字
        String downloadName = fileName+".zip";
        getResponse().setContentType("multipart/form-data");
        //压缩包的路径
        String zipFilePath = getRequest().getSession().getServletContext()
                .getRealPath("/")+ "download/" + downloadName;
        
        FileInputStream fin = new FileInputStream(zipFilePath);
        
        downloadName = URLEncoder.encode(downloadName, "UTF-8");
        getResponse().setHeader("Content-Disposition", "attachment;fileName=" + downloadName);
        getResponse().setContentLength(fin.available());
        
        OutputStream out = getResponse().getOutputStream();
        
        byte[] buf = new byte[8*1024];
        int len;
        while ((len = fin.read(buf)) != -1) {
            out.write(buf, 0, len);
        }
        out.flush();
        out.close();
        fin.close();

        //文件工具类,删除项目中download目录中的临时文件
        FileUtil.delAllFile(downloadPath);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值