不多说,直接看,首先是页面jsp代码
<a href="${pageContext.request.contextPath }/downlowd.do">
<img alt="" src="C:\一级目录\二级目录\201205051340364510870879724.jpg" width="250" >
</a>
接下来是cotroller层代码
@RequestMapping("downlowd.do")
public void downlowd(HttpServletRequest request,HttpServletResponse response) throws Exception{
//要下载文件的文件名
String realName="201205051340364510870879724.jpg";
download(request, response,realName);
}
private void download(HttpServletRequest request,
HttpServletResponse response, String realName) throws Exception {
//输入输出流
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
//文件放置路径
String downLoadPath = "C:\\一级目录\\二级目录\\" + realName;
long fileLength = new File(downLoadPath).length();
//设置响应头
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
response.setHeader("Content-disposition", "attachment; filename="
+ new String(realName.getBytes("utf-8"), "ISO8859-1"));
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();
}
这样页面点击图片时就能下载图片了,但是要注意一下页面编码要对应响应头设置的代码,不然就会出现乱码哦