您的位置:首页 > 编程语言 > Java开发

[Java Web]服务器获取远程文件并Zip打包给客户端下载

2017-05-18 10:23 2291 查看
一、应用场景

客服端请求下载,服务器B从服务器A中获得远程文件Url,服务器B通过服务器A获取的Url拿到文件后,在服务器B中处理,进行Zip打包,并在客户端中响应给客户端,完成Zip文件下载。

二、思路代码

File file1 = new File(“这里使用File构造方法实例化File对象”);

File file2 = new File(“这里使用File构造方法实例化File对象”);

File [] tarFile = {file1,file2};//将多个文件放入File数组

String zipName = doZIP("zipname",tarFile);//这里,我写了一个将多个文件打包为zip的方法doZip(),doZip()返回生成的zip路径

response.setCharacterEncoding("utf-8");//设置编码统一
response.setContentType("multipart/form-data");//设置multipart
//响应头部
response.setHeader("Content-disposition", "attachment;filename=order_" + “设置一个文件名” + ".zip");
InputStream inputStreamzip = new FileInputStream(new File(zipName));//通过zip路径实例化inputStream流

OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStreamzip.read(b)) > 0) {
os.write(b, 0, length);
}
os.close();
inputStreamzip.close();


接下来就是doZip()方法:

/*文件打包zip*/
public String doZIP(String zipname, File [] files) throws Exception{
//doZIP(命名的打包文件名,传递过来的File数组)
byte[] buffer = new byte[1024];

String strZipName = zipname;

ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipName));

for(int i=0;i<files.length;i++) {

FileInputStream fis = new FileInputStream(files[i]);

out.putNextEntry(new ZipEntry(files[i].getName()));

int len;

//读入需要下载的文件的内容,打包到zip文件

while((len = fis.read(buffer))>0) {

out.write(buffer,0,len);

}

out.closeEntry();

fis.close();

}

out.close();

return strZipName;
}


这里注意一下,打包为zip我用了两个包

import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


整体,其实还是,使用zip包,对File数组进行处理,将数组中的所用文件循环处理,一起打包为zip。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: