下載檔案的寫法
阿新 • • 發佈:2018-11-12
@GetMapping("/download") public void download(String fid, HttpServletResponse response) throws Exception { if (StringUtils.isBlank(fid)) { throw new AIPGException("檔案ID為空"); } long id = Long.parseLong(fid); FileInfo fileInfo = fileOperationService.getFileInfo(id); if (fileInfo == null) { throw new Exception("該檔案不存在"); } String fileName = fileInfo.getFileName(); byte[] data = fileOperationService.download(id); response.setContentType("application/octet-stream");//告訴瀏覽器輸出內容為流 fileName = new String(fileName.getBytes(), "utf-8"); response.setHeader("Content-disposition", "attachment;filename=" + fileName); try (OutputStream os = response.getOutputStream()) { os.write(data); os.flush(); } }
前臺JS程式碼
if (layEvent === 'down') {
location.href = BASE_CONTEXT_PATH + '/file/download.dsr?fid=' + data.FILE_ID;
通過這種方法可以實現對檔案的下載功能。