突然更改需求,说要下载图片。无脑了其实文件上传下载是一家的,但是我们用的比较多的还是文件上传。因为上传之后很少下载 在服务器上直接运行 不要就删除了。今天做了一个demo出来为大家分享分享
注意:要保证项目中 有目录的存在以及路径的存在
@RequestMapping(value="/download",method=RequestMethod.GET)
public void download(HttpServletRequest request,
HttpServletResponse response) throws Exception {
// String storeName = "Spring3.xAPI_zh.chm";
String storeName="IMG_2016-07-1402a1c107-8212-4c9d-8379-f4382d8b241e.png";
String contentType = "application/octet-stream";
AdvertsingContorller.download(request, response, storeName, contentType);
}
//文件下载 主要方法
public static void download(HttpServletRequest request,
HttpServletResponse response, String storeName, String contentType
) throws Exception {
request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
//获取项目根目录
String ctxPath = request.getSession().getServletContext()
.getRealPath("");
//获取下载文件露肩
String downLoadPath = ctxPath+"/resources/goods/"+ storeName;
//获取文件的长度
long fileLength = new File(downLoadPath).length();
//设置文件输出类型
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename="
+ new String(storeName.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();
}