public
Created

Servlet for decode base64 of images. You would change content type for others type.

  • Download Gist
Base64Servlet.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
package cl.puas.web.servlet;
 
import sun.misc.BASE64Decoder;
 
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
 
public class Base64Servlet extends HttpServlet {
 
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String imageBase64 = req.getParameter("base64");
OutputStream out = resp.getOutputStream();
writeOutputStream(imageBase64, out);
 
resp.setContentType("image/png");
resp.setHeader("Pragma", "");
resp.setHeader("Cache-Control", "");
resp.setHeader("Content-Disposition", "inline; fileName=image.png");
}
 
private void writeOutputStream(String value, OutputStream outputStream) throws IOException {
BASE64Decoder decoder = new BASE64Decoder();
byte[] imgBytes = decoder.decodeBuffer(value);
BufferedImage bufImg = ImageIO.read(new ByteArrayInputStream(imgBytes));
ImageIO.write(bufImg, "png", outputStream);
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.