您的位置:首页 > 编程语言 > Java开发

java 文件下载

2016-06-14 16:56 519 查看
文件下载,无非是通过流读取文件然后写出文件

@RequestMapping("/download")
@ResponseBody
//filename 为上传存的文件名称,例如:201601011111_2345.png
public  void downloadFile(String filename, HttpServletResponse response,HttpServletRequest request)
throws IOException {
String destpath = "";
destpath = request.getRealPath("/upload/images") + File.separator;
filepath = destpath + filename;
File file = new File(filepath);

response.setContentType("multipart/form-data;charset=utf-8");
//防止乱码
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("GBK"), "ISO8859-1"));
response.setCharacterEncoding("utf-8");
InputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] b = new byte[fis.available()];
fis.read(b);
response.getOutputStream().write(b);
response.getOutputStream().flush();
response.getOutputStream().close();
response.flushBuffer();
fis.close();
}


注意:这种方式下载只能通过window.location.href=”download/downloadFile.do”的方式,不能通过ajax来调用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 文件下载 file