如何在spring boot controller中返回一个文件以及响应消息?

时间:2016-10-22 11:59:39

标签: file spring-boot controller

我需要从Spring Boot @Controller返回 PDF文档以及打开它所需的密码。 我将文件名设为 PathParam user/document/{filename}

我如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

没有什么特别的弹簧启动,它用一个很好的旧的Spring MVC来处理。

This other answer from @Infeligo解释说:

@RequestMapping(value = "user/document/{filename}", method = RequestMethod.GET)
public void getFile(
    @PathParam("filename") String fileName, 
    HttpServletResponse response) {
    try {
      // get your file as InputStream
      InputStream is = ...;
      // copy it to response's OutputStream
      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");
    }
}

您可以在标题字段中设置密码(需要多少安全保护?):

response.addHeader("pdf_password", "thisIsThePassword");