前言
单文件下载,需要引用 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(); } }