java post下载文件 zip批量压缩文件

文章借鉴:https://blog.csdn.net/zhangzeyuaaa/article/details/52823238


用post请求生成from表单提交请求下载了一下

前台代码:
// post下载,构建from表单以post方式下载
      $("#downloadform").remove();  
        var form = $("<form>");// 定义一个form表单  
        form.attr("id", "downloadform");  
        form.attr("style", "display:none");  
        form.attr("target", "");  
        form.attr("method", "post");  
        form.attr("action", contextPath+'/sa/orderformController/downloadOrderShp.do');  
        var input1 = "<input type='hidden' name='path' value='"+geoJsonPath+"' />";  
        form.append(input1);  
        $("body").append(form);// 将表单放置在web中  
        form.submit();// 表单提交   

后台代码:

下载文件的工具类,传要下载的文件路径filePath,文件名称returnName(这个一定要new String转换一下。不然和浏览器编码不同响应到前台会乱码。)。

 public static void fileDownload(String filePath, String returnName,
    HttpServletResponse response, HttpServletRequest request) throws IOException{
   
    String agent = request.getHeader("User-Agent").toUpperCase();

response.setContentType("application/octet-stream;charset=UTF-8");

response.setHeader("Content-type", "application-download");//这个是附件下载 部分文件浏览器会直接读取
// 设置响应头,控制浏览器下载文件
response.setHeader("content-disposition", "attachment;filename="
+ URLEncoder.encode(returnName, "utf-8"));
FileInputStream in1 = new FileInputStream(filePath);
OutputStream out = response.getOutputStream();
byte[] bytes = new byte[5 * 1024];
int len = 0;
while ((len = in1.read(bytes)) != -1) {
out.write(bytes, 0, len);
}
in1.close();
out.close();
out.flush();

    }


在粘一处批量压缩文件的工具类

输出流,我是创建了一个FileOutputStream(参数是响应生成的zip格式结尾的压缩包全路径)来使用的。然后就是集合File格式。

public static void writeZipFile(OutputStream ous, List<File> fileList) {
ZipOutputStream zos = new ZipOutputStream(ous);
byte[] buf=new byte[1024];
int readLen = -1;
try{
for(File file : fileList){
ZipEntry ze = new ZipEntry(file.getName());
ze.setSize(file.length());
ze.setTime(file.lastModified());
zos.putNextEntry(ze);
InputStream is = new BufferedInputStream(new FileInputStream(file));
// 读取文件流,写入到zip
while ((readLen = is.read(buf, 0, 1024))!=-1) {
zos.write(buf, 0, readLen);
}
is.close();
}
}catch(IOException e){
e.printStackTrace();
}finally{
try {
zos.close();
ous.close();
} catch (IOException e) {
}
}

}

压缩文件一定要注意,流的关闭。不然会导致压缩文件下载后,文件虽然可以用,打开压缩包弹出警告框。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值