Java如何通过controller下载文件

走着路睡觉
  • java
小于 1 分钟


@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
public void getFile(
    @PathVariable("file_name") String fileName, 
    HttpServletResponse response) {
    try {
      // 获取你的文件流
      InputStream is = ...;
      // 把文件流复制到 esponse.getOutputStream()
      org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
      response.flushBuffer();
    } catch (IOException ex) {
      log.info("Error writing file to output stream. Filename was '{}'", fileName, ex);
      throw new RuntimeException("IOError writing file to output stream");
    }

}
上次编辑于:
贡献者: zhaojingbo
Loading...