參考地址:java
http://www.jb51.net/article/84691.htmspring
//下載績效操做手冊
@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");
mvc
// 若是使用 springmvc 的方式就是 第三種方式,那麼下面的 2行代碼要註釋掉,不然報錯 app
// 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);this
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);.net
// 第二種下載方式
// 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;
}orm