Convert byte[] to Base64 string for data URI

后端 未结 5 1560
名媛妹妹
名媛妹妹 2020-12-02 16:55

I know this has probably been asked 10000 times, however, I can\'t seem to find a straight answer to the question.

I have a LOB stored in my db that represents an i

5条回答
  •  臣服心动
    2020-12-02 17:50

    You may also want to consider streaming the images out to the browser rather than encoding them on the page itself.

    Here's an example of streaming an image contained in a file out to the browser via a servlet, which could easily be adopted to stream the contents of your BLOB, rather than a file:

      public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
      {
        ServletOutputStream sos = resp.getOutputStream();
        try {
          final String someImageName = req.getParameter(someKey);
    
          // encode the image path and write the resulting path to the response
          File imgFile = new File(someImageName);
    
          writeResponse(resp, sos, imgFile);
        }
        catch (URISyntaxException e) {
          throw new ServletException(e);
        }
        finally {
          sos.close();
        }
      }
    
      private void writeResponse(HttpServletResponse resp, OutputStream out, File file)
        throws URISyntaxException, FileNotFoundException, IOException
      {
        // Get the MIME type of the file
        String mimeType = getServletContext().getMimeType(file.getAbsolutePath());
        if (mimeType == null) {
          log.warn("Could not get MIME type of file: " + file.getAbsolutePath());
          resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
          return;
        }
    
        resp.setContentType(mimeType);
        resp.setContentLength((int)file.length());
    
        writeToFile(out, file);
      }
    
      private void writeToFile(OutputStream out, File file)
        throws FileNotFoundException, IOException
      {
        final int BUF_SIZE = 8192;
    
        // write the contents of the file to the output stream
        FileInputStream in = new FileInputStream(file);
        try {
          byte[] buf = new byte[BUF_SIZE];
          for (int count = 0; (count = in.read(buf)) >= 0;) {
            out.write(buf, 0, count);
          }
        }
        finally {
          in.close();
        }
      }
    

提交回复
热议问题