How to offer download of local PDF file in Java?

前端 未结 3 1441
旧巷少年郎
旧巷少年郎 2021-01-16 11:37

I have JBoss running as application server and somewhere on my HD there is a PDF file, that gets created when the user clicks on a specific action. Let\'s say the file is he

3条回答
  •  执念已碎
    2021-01-16 12:03

    as i wrote on Is there a common way to download all types of files in jsp?

    you can use something like this:

    public HttpServletResponse getFile (HttpServletRequest request ,HttpServletResponse httpServletResponse, .......){
              HttpServletResponse response = httpServletResponse;
              InputStream in =/*HERE YOU READ YOUR FILE AS BinaryStream*/
    
              String filename = "";
              String agent = request.getHeader("USER-AGENT");
              if (agent != null && agent.indexOf("MSIE") != -1)
              {
                filename = URLEncoder.encode(/*THIS IS THE FILENAME SHOWN TO THE USER*/, "UTF8");
                response.setContentType("application/x-download");
                response.setHeader("Content-Disposition","attachment;filename=" + filename);
              }
              else if ( agent != null && agent.indexOf("Mozilla") != -1)
              {
                response.setCharacterEncoding("UTF-8");
                filename = MimeUtility.encodeText(/*THIS IS THE FILENAME SHOWN TO THE USER*/, "UTF8", "B");
                response.setContentType("application/force-download");
                response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
              }
    
    
              BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
              byte by[] = new byte[32768];
              int index = in.read(by, 0, 32768);
              while (index != -1) {
                  out.write(by, 0, index);
                  index = in.read(by, 0, 32768);
              }
              out.flush();
    
              return response;
    }
    

    UPDATE:

    Dont forget that you can use the InputStream as this:

    // read local file into InputStream
    InputStream inputStream = new FileInputStream("c:\\SOMEFILE.xml");
    

    or you can use it even like this

    //read from database
    Blob blob = rs.getBlob(1);
    InputStream in = blob.getBinaryStream();
    

提交回复
热议问题