下面为下载所有类型的资源的代码!
public ActionForward downloadData(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = null;
String newsId = request.getParameter(Constants.NEWS_ID).trim();
request.setCharacterEncoding("gb2312");
response.setContentType("text/html;charset=gb2312");
ActionErrors errors = new ActionErrors();
try {
NewsCnt cnt = this.showService.searchNews(newsId);
String filePath = cnt.getCntUrl();
// filePath = URLEncoder.encode(filePath, "UTF-8");
log.debug("----->>>>filePaht = " + filePath);
// // 设置为下载
String fileName = filePath.substring(
filePath.lastIndexOf("//") + 1, filePath.lastIndexOf("."));
String postfix = filePath.substring(filePath.lastIndexOf(".") + 1,
filePath.length());
log.debug("----->>>>fileName = " + fileName);
response.setContentType("application/x-download");
response.addHeader("Content-Disposition", "attachment;filename="
+ "download." + postfix);
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.flush();
log.debug("资料下载成功!");
forward = mapping.findForward("downloadDataPath");
} catch (Exception e) {
log.debug("资料下载时出现异常:" + e.getMessage());
errors.add(Constants.ERROR_KEY, new ActionError(
"download.data.exception", MessageResources
.getMessageResources(Constants.RESOURCE_KEY)));
forward = mapping.getInputForward();
}
return forward;
}
这里简单说下需要注意的几点问题!
1.定义输出类型,和设置输出文件头
response.setContentType("application/x-download");
response.addHeader("Content-Disposition", "attachment;filename="
+ "download." + postfix);
(1) 当下载excel文件时设置如下:
// 设定输出文件头
response.setHeader("Content-disposition",
"attachment;filename=module.xls");
// 定义输出类型
response.setContentType("application/msexcel");
(2)当下载word文件时设置如下:
// 设定输出文件头
response.setHeader("Content-disposition",
"attachment;filename=module.doc");
// 定义输出类型
response.setContentType("application/msword");
2.文件名不能为中文(这个到现在还没弄清楚)
response.addHeader("Content-Disposition", "attachment;filename="
+ "download." + postfix);
即"download"不能为中文,开始试过用源文件名来做下载的文件名,但是当文件名包含中文就不能下载
因此,将文件名改成了"download"。上面postfix为扩展名
3.到现在,文件头的设置和输出类型的定义,还没完全弄清楚