JAVA中文件下载和文件批量下载方法

JAVA中的文件下载:

/**

* 文件下载
* @param request
* @param response
* @param filePath 文件路径
* @param filename 下载时文件名称
*/
public static void downLoadFile(HttpServletRequest request,HttpServletResponse response,String filePath,String filename){
try {
File file=new File(filePath);
// 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称 用于浏览器的下载框中自动显示的文件名
String userAgent =request.getHeader("User-Agent");
if(userAgent.contains("MSIE")||userAgent.contains("Trident")){
filename= java.net.URLEncoder.encode(filename,"UTF-8");
}else{
filename=new String(filename.getBytes("utf-8"),"iso8859-1");
}
response.addHeader("Content-Disposition", "attachment;filename=" +filename );
//response.setContentType("application/vnd.ms-excel");
response.setContentType("multipart/form-data");
byte[] b = new byte[1024];
int len=0;
FileInputStream fs=new FileInputStream(file);
PrintWriter writer = response.getWriter();
while ((len = fs.read()) != -1) {
writer.write(len);
}
fs.close();
writer.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

JAVA中批量下载文件,将下载多个文件打包成zip文件下载。
//批量文件下载(将多个文件打包成zip包下载)
public static void batchDownLoadFile(HttpServletRequest request,HttpServletResponse response,String filename,String[] filepath,String[] documentname,String loginname){
byte[] buffer = new byte[1024];
Date date=new Date();
//生成zip文件存放位置
String strZipPath = Constant.exportAddress +loginname+date.getTime()+".zip";
File file=new File(Constant.exportAddress);
if(!file.isDirectory() && !file.exists()){
//创建单层目录
// f.mkdir();
// 创建多层目录
file.mkdirs();
}
try {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));
// 需要同时下载的多个文件
for (int i = 0; i < filepath.length; i++) {
File f=new File(filepath[i]);
FileInputStream fis = new FileInputStream(f);
System.out.println(documentname[i]);
out.putNextEntry(new ZipEntry(documentname[i]));
//设置压缩文件内的字符编码,不然会变成乱码
out.setEncoding("GBK");
int len;
// 读入需要下载的文件的内容,打包到zip文件
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.closeEntry();
fis.close();
}
out.close();
PublicMethod.downLoadFile(request, response, strZipPath, filename+".zip");
File temp=new File(strZipPath);
if(temp.exists()){
temp.delete();
}
} catch (Exception e) {
System.out.println("文件下载错误");
}
}



  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奔跑中的小象

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值