jsp页面js代码:
function downloadAttached(){
var id = [];
id.push(infoid);
var options = {};
options.action = "${pageContext.request.contextPath}/DocumentController/downloadattached";
options.argname1="id";
options.argvalue1=id.join(',');
filedownload(options);
parent.$.messager.progress('close');
}
控制层java相关代码
public ModelAndView DownloadAttached(HttpServletRequest request, HttpServletResponse response,String id,String ie) throws Exception{
String toClient=attService.downloadAttached(request, response, id, projectName);
String[] split = toClient.split("/");
String storeName = toClient;
String realName = split[split.length - 1];
String contentType = "application/x-zip-compressed";
try {
excelExport.download(request,response,storeName,contentType,realName,ie);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//download方法
public static void download(HttpServletRequest request,
HttpServletResponse response, String storeName, String contentType,
String realName, String ie) throws Exception {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
String ctxPath = request.getSession().getServletContext()
.getRealPath("/");
String downLoadPath = ctxPath + storeName;
long fileLength = new File(downLoadPath).length();
response.setContentType(contentType);
String finalFileName;
if (ie.equals("1")) {
finalFileName = java.net.URLEncoder.encode(realName, "UTF8");
} else {
finalFileName = new String(realName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setHeader("Content-disposition", "attachment; filename="
+ finalFileName);
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
}
打包下载代码:将压缩包文件下载到服务器项目中的目录下然后用户去下载
private static String downpath = "down/";
public static String compress(String[] path,String strZipName) throws Exception {
byte[] buffer = new byte[1024];
String zippath = PathUtil.combine(PathUtil.getWebRootPath(), downpath);
//strZipName中有空格会生成、下载不成功
String zipName=zippath+strZipName+".zip";
String returnzipname=downpath+strZipName+".zip";
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipName));
File[] file1= new File[path.length];
for(int i=0;i<file1.length;i++) {
file1[i]=new File(path[i]);
String combine = PathUtil.combine(PathUtil.getWebRootPath(),
file1[i].toString());
FileInputStream fis = new FileInputStream(combine);
out.putNextEntry(new ZipEntry(file1[i].getName()));
int len;
while((len = fis.read(buffer))>0) {
out.write(buffer,0,len);
}
out.closeEntry();
fis.close();
}
out.close();
return returnzipname;
}