如何读取Servlet中的图像(或其他文件)并将其编码为base64

在servlet中,我必须从磁盘读取映像文件,将其编码为Base64,然后发送回客户端。 因为我只找到iOS,Python和其他一些类型的样本(主要是所有类似的方式)我想我在这里发布我的代码来帮助其他人;)

警告! 这应该仅适用于最大2GB的文件: ByteBuffer设置容量只需要一个int

为什么如此复杂以及为什么要将完整的图像读入内存? 一个更简单的解决方案:

 protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder(); enc.encode(new FileInputStream("/path/to/file.whatever"), response.getOutputStream()); } 
 protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { FileInputStream in = null; try { File file = new File(getServletContext().getRealPath("//")); ByteBuffer buff = ByteBuffer.wrap(new byte[(int)image.length() + (image.length() % 1024 > 0 ? 1024 : 0)]); byte[] b = new byte[1024]; in = new FileInputStream(file); while(in.read(b) != -1) { buff.put(b); } response.getWriter().write(Base64.encode(buff.array())); } catch(Exception e) { String msg = "Fehler beim lesen des Bildes"; LOG.log(Level.SEVERE, msg, e); response.sendError(500, msg); return; } finally { if(in != null) in.close(); } } 

警告! 这应该仅适用于最大2GB的文件: ByteBuffer设置容量只需要一个int