当用户一次下载多个文件时。普通情况是,每下载一个文件,均要弹出一个下载的对话框。这给用户造成了非常大不便。
比較理想的情况是,用户选择多个文件后。server后端直接将多个文件打包为zip。以下贴出实现代码。
前端Javascript代码(使用Javascript创建表单。通过提交表单的方式訪问后端的MultiDownload):
var tmpForm = document.createElement("form");
tmpForm.id = "form1" ;
tmpForm.name = "form1" ;
document.body.appendChild(tmpForm);
var tmpInput = document.createElement("input");
// 设置input对应參数
tmpInput.type = "text";
tmpInput.name = "fileUrls" ;
tmpInput.value = downloadUrls;
// 将该输入框插入到 tmpform 中
tmpForm.appendChild(tmpInput);
tmpForm.action= "servlet/MultiDownload" ;
tmpForm.method= "get";
tmpForm.submit();
//从html从移除该form
document.body.removeChild(tmpForm);
后端MultiDownload代码:
public class MultiDownload extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public MultiDownload() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String strArray = null;
strArray = request.getParameter("fileUrls");
//传递到servlet时,默认将编码转换为ISO-8859-1,将其又一次转码为GBK
strArray=new String(strArray.getBytes("ISO-8859-1"), "GBK");
String[] filePathArray = strArray.split(",");
String zipFileName = "product.zip";
response.setContentType("application/x-msdownload" ); // 通知客户文件的MIME类型:
response.setHeader("Content-disposition" , "attachment;filename=" + zipFileName);
//要下载的文件文件夹
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
for (String filePath : filePathArray) {
File file = new File(filePath);
doZip(file, zos);
}
zos.close();
}
/**
* 打包为 zip 文件
* @param file 待打包的文件
* @param zos zip zip输出流
* @throws IOException
*/
private void doZip(File file, ZipOutputStream zos)
throws IOException {
if(file.exists()) {
if (file.isFile()) {
//假设是文件,写入到 zip 流中
zos.putNextEntry(new ZipEntry(file.getName()));
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int r = 0;
while ((r = fis.read(buffer)) != -1) {
zos.write(buffer, 0, r);
}
zos.flush();
fis.close();
} else {
//假设是文件夹。
递归查找里面的文件 String dirName = file.getName() + "/"; zos.putNextEntry(new ZipEntry(dirName)); File[] subs = file.listFiles(); for (File f : subs) { makeZip(f, dirName, zos); } } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }