Spring 3.0 Java REST 返回 PDF 文档

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11800763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:25:13  来源:igfitidea点击:

Spring 3.0 Java REST return PDF document

javaspringmodel-view-controllerrest

提问by Krishnan J

I have a PDF document generated in the backend. I want to return this using Spring MVC REST framework. What should the MarshallingView and ContentNegotiatingViewResolver look like?

我在后端生成了一个 PDF 文档。我想使用 Spring MVC REST 框架返回它。MarshallingView 和 ContentNegotiatingViewResolver 应该是什么样的?

Based on a sample I found, the controller would have this as the return:

根据我发现的一个示例,控制器会将其作为返回值:

return new ModelAndView(XML_VIEW_NAME, "object", 
    byteArrayResponseContainingThePDFDocument);

-thank you.

-谢谢。

回答by Biju Kunjummen

You can define your method to take in explicit HttpServletRequestand HttpServletResponseand stream to the HttpServletResponse directly, this way:

你可以定义你的方法采取明确HttpServletRequestHttpServletResponse和流直接HttpServletResponse的,是这样的:

@RequestMapping(value="/pdfmethod", produces="application/pdf")
public void pdfMethod(HttpServletRequest request, HttpServletResponse response){
    response.setContentType("application/pdf");
    InputStream inputStream = null;
    OutputStream outputStream = null;
    try{
        inputStream = getInputStreamFromYourPdfFile();
        outputStream = response.getOutputStream();
        IOUtils.copy(inputStream, outputStream);
    }catch(IOException ioException){
        //Do something or propagate up..
    }finally{
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
    }
}