1. 程式人生 > 實用技巧 >Header 中的檔案型別設定,瀏覽器下載檔案,下載excel,附件

Header 中的檔案型別設定,瀏覽器下載檔案,下載excel,附件

下載檔案為excel只需要設定HttpServletResponse 
@RequestMapping("/download")
public void doDownLoad(HttpServletResponse response) throws IOException {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("test", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), UserEntity.class).sheet("模版1").doWrite(getData());
EasyExcel.write(response.getOutputStream(), UserEntity.class).sheet("模版2").doWrite(getData());
}



如果要將查詢結果匯出到Excel,只需將頁面的Context-Type修改一下就可以了:
header( "Content-Type: application/vnd.ms-excel">
如果希望能夠提供那個開啟/儲存的對話方塊,Content-Disposition引數,Content-Disposition引數本來是為了在客戶端另存檔案時提供一個建議的檔名,
但是考慮到安全的原因,就從規範中去掉了這個引數
Content-Disposition引數:
attachment --- 作為附件下載
inline --- 線上開啟
具體使用如:header("Content-Disposition: inline; filename=檔名.mp3");
Header("Content-Disposition:attachment;filename=test.xls");
其實IE是根據Content-Disposition中filename這個段中檔名的字尾來識別這個檔案型別的,所以,

如果有很多種檔案型別的時候,可以將Content-Type設定為二進位制模式的:
Header("Content-type: application/octet-stream");
示例:
<?