一、果需要从服务器下载文件,首先应该对文件进行压缩,
二、注意事项:1、不应该在服务器创建临时的压缩文件,这样比较浪费服务器硬盘资源
2、读取文件时,一定要加上服务器地址 + 文件路径 + 文件名.后缀名
三、实现细节
/**
*文件转byte[]
*
*@paramfile
*
*@return
*/
private byte[] getBytes(Filefile){
byte[] buffer=null;
try{
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[]b=new byte[1000];
int n;
while((n=fis.read(b))!=-1){
bos.write(b,0,n);
}
fis.close();
bos.close();
buffer=bos.toByteArray();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
returnbuffer;
}
/**
*批量下载前进行文件压缩
*
*@param fileList 准备压缩文件的集合
*/
private Map<String,byte[]> zipFile(List<File>fileList) throws IOException{
Map<String,byte[]> map=new HashMap<>(16);
for(Filefile:fileList){
String name = file.getName();
byte[] data = getBytes(file);
map.put(name,data);
}
return map;
}
// 打开输出流,输出至需要下载的浏览器端
String zipName="下载完成后显示的文件名字";
response.reset();
zipName=java.net.URLEncoder.encode(zipName,"UTF-8");
// 设置请求头,触发下载器
response.setContentType("application/x-msdownload;charset=utf-8");
response.setHeader("Content-Disposition","attachment;filename="+zipName+".zip");
// 打开输出流
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
BufferedOutputStream bos = new BufferedOutputStream(zos);
// 压缩每一条需要下载的数据
for(Map.Entry<String,byte[]>entry:files.entrySet()){
//每个条目文件名
String fileName = entry.getKey();
//这个zip文件的字节
byte[]file=entry.getValue();
BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(file));
zos.putNextEntry(newZipEntry(fileName));
int len=0;
byte[] buf = new byte[10*1024];
while((len=bis.read(buf,0,buf.length))!=-1){
bos.write(buf,0,len);
}
bis.close();
bos.flush();
}
// 关闭下载的输出流
bos.close();