前言
單文件下載,需要引用 SpringBoot項目實現單文件上傳(一)中的配置文件信息和工具類。可以直接點擊該連接查看即可。
單文件下載
單文件下載比起單文件上傳而言顯得更加簡單,廢話不多說,直接上代碼。
/** * * @param filePath 文件路徑地址 * @param response */
@GetMapping("/downloadFile") @ApiOperation(value = "單文件下載") public void download(@RequestParam(value = "filePath") String filePath, HttpServletResponse response) { try ( InputStream inputStream = new FileInputStream(new File(filePath)); OutputStream outputStream = response.getOutputStream() ) { //設置內容類型爲下載類型 response.setContentType("application/x-download"); //設置請求頭 和 文件下載名稱 response.addHeader("Content-Disposition", "attachment;filename=" + filePath); //用 common-io 工具 將輸入流拷貝到輸出流 IOUtils.copy(inputStream, outputStream); outputStream.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }