SpringBoot如何實(shí)現(xiàn)文件下載
SpringBoot文件下載
在寫java 的文件下載的時(shí)候一直拋出異常
getOutputStream() has already been called for this response
直到使用了下面的方法
/**
* 稿源周報(bào)excel表格下載
* @return
*/
@RequestMapping(value = "/downExcel", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
@ResponseBody
public String downExcel(HttpServletResponse response) throws UnsupportedEncodingException {
LocalDate end = LocalDate.now();
LocalDate start = end.minusDays(14);
String filename = "稿源抓取周報(bào)-" + end.format(DateTimeFormatter.ISO_DATE) + ".xlsx";
String filepath = "files/" + filename;
writeExcelFile(start, end, filepath);
// 如果文件名不為空,則進(jìn)行下載
if (filename != null) {
File file = new File(filepath);
// 如果文件存在,則進(jìn)行下載
if (file.exists()) {
// 配置文件下載
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// 下載文件能正常顯示中文
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
// 實(shí)現(xiàn)文件下載
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("Download successfully!");
return "successfully";
} catch (Exception e) {
System.out.println("Download failed!");
return "failed";
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return "";
}后來又出現(xiàn)了 一個(gè)問題就是后臺(tái)不拋出異常,也不出現(xiàn)下載的提示發(fā)現(xiàn)了以下問題
如果要用ajax 發(fā)送的話,則瀏覽器沒有任何反應(yīng) 因?yàn)閍jax返回的格式是 字符的格式
$.ajax({
url:"/down/downExcel",
type:"GET",
dataType:"json",
success:function(result){
}}); 換成:
window.location.href="/down/downExcel" rel="external nofollow" ;
OK!

總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
MyBatis使用自定義TypeHandler轉(zhuǎn)換類型的實(shí)現(xiàn)方法
這篇文章主要介紹了MyBatis使用自定義TypeHandler轉(zhuǎn)換類型的實(shí)現(xiàn)方法,本文介紹使用TypeHandler 實(shí)現(xiàn)日期類型的轉(zhuǎn)換,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-10-10
配置hadoop環(huán)境mapreduce連接不上hdfs解決
這篇文章主要為大家介紹了配置hadoop環(huán)境mapreduce連接不上hdfs解決方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10
SpringBoot整合RabbitMQ處理死信隊(duì)列和延遲隊(duì)列
這篇文章將通過示例為大家詳細(xì)介紹SpringBoot整合RabbitMQ時(shí)如何處理死信隊(duì)列和延遲隊(duì)列,文中的示例代碼講解詳細(xì),需要的可以參考一下2022-05-05
System.getProperty(user.dir)定位問題解析
System.getProperty(user.dir) 獲取的是啟動(dòng)項(xiàng)目的容器位置,用IDEA是項(xiàng)目的根目錄,部署在tomcat上是tomcat的啟動(dòng)路徑,即tomcat/bin的位置,這篇文章主要介紹了System.getProperty(user.dir)定位問題,需要的朋友可以參考下2023-05-05

