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

spring mvc 文件下载

2017-01-03 00:00 211 查看
参考地址:
http://www.jb51.net/article/84691.htm
//下载绩效操作手册
@RequestMapping("/down/pfmceplan.do")
public ResponseEntity<byte[]> downPfmceplan(HttpServletRequest request,HttpServletResponse response) throws Exception{

String fileName="绩效操作shouceV1.0.zip";

response.reset();
response.setCharacterEncoding("utf-8");

// 如果使用 springmvc 的方式就是 第三种方式,那么下面的 2行代码要注释掉,否则报错

// connetct reset()...连接错误 ,有冲突
//response.setContentType("application/octet-stream; charset=utf-8");
//response.setHeader("Content-Disposition", "attachment; filename="
// + fileName);

HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

String path = Thread.currentThread().getContextClassLoader()
.getResource("").getPath();
// 求出 根项目的路径
String pathRealroot=path.substring(0, path.lastIndexOf("WEB-INF"))+"assets/"+"download/";

File downPath=new File(pathRealroot
+File.separator + fileName);

System.out.println("=================>>>>>>>>>>>>>>>"+downPath);

// 第三种 下载方式
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(downPath),
headers, HttpStatus.CREATED);

// 第二种下载方式
// OutputStream os = response.getOutputStream();
// os.write(FileUtils.readFileToByteArray(downPath));
// os.flush();
// os.close();
//return null;

/*
* 原生下载方式 第一种
* InputStream inputStream = new FileInputStream(downPath);
*
*
*
*
*
* byte[] b = new byte[2048]; int length; while ((length =
* inputStream.read(b)) > 0) { os.write(b, 0, length); } os.flush();
*
* // 这里主要关闭。 os.close();
*
* inputStream.close();
*/

// 返回值要注意,要不然就出现下面这句错误!
// java+getOutputStream() has already been called for this response
//return null;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: