完整的 Spring Boot 下載文件示例代碼

package com.alibaba.alpha.download; import com.alibaba.alpha.mapper.UiTestCaseMapper; import com.alibaba.alpha.model.UiTestCase; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; @Controller public class DownloadController { @Autowired UiTestCaseMapper uiTestCaseMapper; /** * /downloadTestCase?testCaseId=${testCaseId} * * @param testCaseId * @param response * @throws Exception */ @GetMapping("/downloadTestCase") public void downloadTestCase(Long testCaseId, HttpServletResponse response) throws Exception { // 1.用例數據 UiTestCase UiTestCase = uiTestCaseMapper.selectByPrimaryKey(testCaseId); String tcName = UiTestCase.getName(); // 2.文件存放路徑 String tmpDir = System.getProperty("user.home") + "/sidejson/"; File tmpDirFile = new File(tmpDir); if (!tmpDirFile.exists()) { tmpDirFile.mkdir(); } // 3.sideJson 文件 String fileName = tmpDir + tcName; File sideJsonFile = new File(fileName); if (!sideJsonFile.exists()) { sideJsonFile.createNewFile(); } FileWriter fileWritter = new FileWriter(fileName, true); fileWritter.write(UiTestCase.getSideJson()); fileWritter.close(); // 配置文件下載 response.setHeader("content-type", "application/octet-stream"); response.setContentType("application/octet-stream"); // 下載文件能正常顯示中文, 可以導入 iRecorder Web IDE中的 .side 文件 String filename = URLEncoder.encode(tcName + ".side", "UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=" + filename); // 實現文件下載 byte[] buffer = new byte[1024]; FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(sideJsonFile); 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! " + fileName); } catch (Exception e) { System.out.println("Download failed! " + fileName); e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章