How to send byte[] as pdf to browser in java web application?

前端 未结 3 2047
無奈伤痛
無奈伤痛 2020-12-01 08:29

In action method (JSF) i have something like below:

public String getFile() {
  byte[] pdfData = ...
  // how to return byte[] as file to web browser user ?
         


        
3条回答
  •  Happy的楠姐
    2020-12-01 08:51

    You just have to set the mime type to application/x-pdf into your response. You can use the setContentType(String contentType) method to do this in the servlet case.
    In JSF/JSP you could use this, before writing your response:

    <%@ page contentType="application/x-pdf" %>
    

    and response.write(yourPDFDataAsBytes()); to write your data.
    But I really advise you to use servlets in this case. JSF is used to render HTML views, not PDF or binary files.

    With servlets you can use this :

    public MyPdfServlet extends HttpServlet {
        protected doGet(HttpServletRequest req, HttpServletResponse resp){
             OutputStream os = resp.getOutputStream();
             resp.setContentType("Application/x-pdf");
             os.write(yourMethodToGetPdfAsByteArray());
        } 
    }
    

    Resources :

    • mimeapplication.net - pdf
    • Javadoc - ServletResponse
    • Javadoc - HttpServlet

提交回复
热议问题