客户需求:点击附件后不打开附件,而是直接下载
实现思想:将附件读入InputStream,并写入OutputStream返回给Response
实现代码:
download.jsp:
<a href="<c:url value="/front/download.do?documentId=${document.id}"/>">${document.name}</a>
downloadController.java:
@RequestMapping("/download.do")
public void download(@RequestParam(value = "documentId",required = true)Long documentId,
ModelMap modelMap,HttpServletRequest request ,HttpServletResponse response){
//保存数据
if(documentId > 0){
//取得附件信息
List<LmsResourceEntity> lmsResourceList = lmsResourceDao.findById(documentId);
for(LmsResourceEntity lmsResource : lmsResourceList){
//取得附件在服务器上的路径(D:/Tomcat7/webapp/...)
String savePath = request.getSession().getServletContext().getRealPath("/") + lmsResource.getUrl();
System.out.println("store path is :" + savePath);
//Response编码设为UTF-8
response.setContentType("text/html;charset=utf-8");
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("设置错误",e);
}
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
long fileLength = new File(savePath).length();
response.setContentType("application/x-msdownload;");
//注意!filename需要转码,否则中文名会显示不了
response.setHeader("Content-disposition", "attachment; filename=" + new String( lmsResource.getName().getBytes("gb2312"), "ISO8859-1" ) );
response.setHeader("Content-Length", String.valueOf(fileLength));
//读取文件
bis = new BufferedInputStream(new FileInputStream(savePath));
//bos设置为Response的OutputStream
bos = new BufferedOutputStream(response.getOutputStream());
//将文件写入bos
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
try {
bis.close();
} catch (IOException e) {
throw new RuntimeException("下载失败",e);
}
if (bos != null)
try {
bos.close();
} catch (IOException e) {
throw new RuntimeException("下载失败",e);
}
}
}
}
else{
System.out.println("文件下载无效documentId");
}
}