java下载多个文件,并打包,为啥我浏览器弹出来的下载链接都不是zip格式,但是如果将该文件修改拓展名为zip,下载文件又都在里面
public static void downLoadZipAllFile(HttpServletRequest request, HttpServletResponse response, List {
OutputStream outp = null;
ZipOutputStream zos = null;
BufferedInputStream bis = null;
try {
outp = response.getOutputStream();
response.setContentType("text/html; charset=UTF-8"); //设置编码字符
response.setContentType("application/octet-stream"); //设置内容类型为下载类型
// response.setContentType("application/zip");// 定义输出类型
String timeSuffix = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String zipFilePath = "D:/ftpHome/" + timeSuffix + "_DataFile.zip";
String filedisplay = zipFilePath;
if (filedisplay.indexOf("/") >= 0) {
filedisplay = filedisplay.substring(filedisplay.lastIndexOf("/") + 1);
} else if (filedisplay.indexOf("\\") >= 0) {
filedisplay = filedisplay.substring(filedisplay.lastIndexOf("\\") + 1);
}
String agent = (String) request.getHeader("USER-AGENT");
// firefox
if (agent != null && agent.indexOf("MSIE") == -1) {
String enableFileName = "=?UTF-8?B?"
+ (new String(Base64.getBase64(filedisplay))) + "?=";
response.setHeader("Content-Disposition",
"attachment; filename=" + enableFileName);
} else {
filedisplay = URLEncoder.encode(filedisplay, "utf-8");
response.addHeader("Content-Disposition",
"attachment;filename=" + filedisplay);
}
try {
File zip = new File(zipFilePath);
if (!zip.exists()) {
zip.createNewFile();
}
zos = new ZipOutputStream(outp);
for (Map map : maps) {
String filePath = map.get("filePath");
String filename = map.get("fileName");
File file = new File(filePath);
if (file.exists()) {
zos.putNextEntry(new ZipEntry(filename));
bis = new BufferedInputStream(new FileInputStream(filePath));
byte[] b = new byte[1024 * 64];
int i = 0;
while ((i = bis.read(b)) > 0) {
zos.write(b, 0, i);
}
zos.closeEntry();
bis.close();
String isDelete = request.getParameter("isDelete");
if ("1".equals(isDelete)) {
file.delete();
}
} else {
outp.write("文件不存在!".getBytes("GBK"));
}
}
zos.close();
bis = new BufferedInputStream(new FileInputStream(zipFilePath));
byte[] buff = new byte[1024 * 64];
bis.read(buff);
outp.write(buff);//输出数据文件
outp.flush();//释放缓存
outp.close();
bis.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
bis.close();
bis = null;
}
if (zos != null) {
zos.close();
zos = null;
}
if (outp != null) {
outp.close();
outp = null;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
然后目前下载的文件的效果如下:
求各位大佬解答一下
回答:原因很简单,你并没有进行压缩,你如果把文件输出到文件夹内,你又没有对这个文件夹进行压缩,传给浏览器,肯定就是没有压缩好的文件夹。你可以选择调用一下压缩软件的接口,把文件压缩一下。也可以选择自己写一个最优二叉树(哈夫曼树),来实现一个压缩算法,不过这样的缺点就是没办法用别的压缩软件打开,只能通过你自己编写的软件打开。你可以去查一下类似7-zip软件,它的压缩算法,或者直接调用它的接口。压缩发送,你现在已经实现了,只是还没有成功压缩好