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

前端 未结 3 2048
無奈伤痛
無奈伤痛 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条回答
  •  暖寄归人
    2020-12-01 09:03

    When sending raw data to the browser using JSF, you need to extract the HttpServletResponse from the FacesContext.

    Using the HttpServletResponse, you can send raw data to the browser using the standard IO API.

    Here is a code sample:

    public String getFile() {
        byte[] pdfData = ...
    
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        OutputStream out = response.getOutputStream();
        // Send data to out (ie, out.write(pdfData)).
    }
    

    Also, here are some other things you might want to consider:

    • Set the content type in the HttpServletResponse to inform the browser you're sending PDF data: response.setContentType("application/pdf");
    • Inform the FacesContext that you sent data directly to the user, using the context.responseComplete() method. This prevents JSF from performing additional processing that is unnecessary.

提交回复
热议问题