简体   繁体   中英

How to display the pdf on a browser?

I have a stream of bytes for a pdf file which I have stored in a session.

@RequestMapping(value = "/start.htm")
    public String start(HttpServletRequest request, Model model)
            throws Exception 
{

// do something
request.getSession().setAttribute(uniqueId,bytesOfaPDF);

return "jspname";
}

Now I have put this in my JSP.

<object id="COB" data="/retrievePdf.htm" type="application/pdf" width="100%" height="100%">

</object>

Now I have to write another method in my controller with the same mapping ( retrievePdf ) which will show PDF.

@RequestMapping(value="/retrievePdf.htm", method=RequestMethod.GET)
    public void retrievePdf(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap)throws OSOSystemException
    {
        byte[] db = (byte[]) request.getSession().getAttribute(uniqueId);

        response.getOutputStream().write(db);

        response.setContentType("application/pdf");
        response.setContentLength(db.length);


    }

But I am not able to understand how I can pass uniqueId to retrievePdf?

How I can achieve this? Thanks in advance.

Pass the unique ID as a query string in the URL

Store the unique id in request

@RequestMapping(value = "/start.htm")
    public String start(HttpServletRequest request, Model model)
            throws Exception 
{

// do something
// storing uniqueId
request.getSession().setAttribute("uniqueId",uniqueId) ;
request.getSession().setAttribute(uniqueId,bytesOfaPDF);

return "jspname";
}

In Jsp append the URL dynamicaally:

<% String uniqueId=request.getSession().getAttribute("uniqueId") ;
   String url = "/retrievePdf.htm?uniqueId="+uniqueId ;
%>

<object id="COB" data="<%=url%>" type="application/pdf" width="100%" height="100%">

</object>

Add requestParam for uniqueId in the below method and process it

@RequestMapping(value="/retrievePdf.htm", method=RequestMethod.GET)
    public void retrievePdf(HttpServletRequest request, HttpServletResponse response, @RequestParam(value="uniqueId",required=true)String uniqueId,ModelMap modelMap)throws OSOSystemException
    {
        byte[] db = (byte[]) request.getSession().getAttribute(uniqueId);

        response.getOutputStream().write(db);

        response.setContentType("application/pdf");
        response.setContentLength(db.length);


    }

Thats all, it will work !!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM