[Java] Upload images and base64

Overview

--Try uploading images with good old tech stack using Servlet / JSP --What I want to do this time is to convert the file sent by multipart / form-data to Base64 on the server side. --Both Servlet and JSP are amateurs

code

Upload screen

--JSP of the upload screen to be displayed first

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Java Sample</title>
  </header>
  <body>
    <h1>Hello</h1>
    <form action="upload" method="post" enctype="multipart/form-data">
      <input type="hidden" name="action_name" value="upload" />
      <input type="file" name="file" />
      <button>Upload</button>
    </form>
  </body>
</html>

--Throw an image to / upload with multipart / form-data

Image acquisition process

--Controller to receive upload request --The base sample is the same, but when ʻaction_name is ʻupload, it feels like calling ʻUploadAction. --This time, we will receive multipart / form-data, so the point is to add @ MultipartConfig`.

package com.example.controller;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.example.action.Action;
import com.example.action.UploadAction;

@WebServlet(urlPatterns = { "/upload" })
@MultipartConfig
public class UploadController extends HttpServlet {

  @Override
  protected void doPost(
    HttpServletRequest request,
    HttpServletResponse response
  )
    throws ServletException, IOException {
    String strActionName = request.getParameter("action_name");
    Action action = getInstance(strActionName);
    String forwardPath = action.execute(request);
    RequestDispatcher rd = request.getRequestDispatcher(forwardPath);

    rd.forward(request, response);
  }
  
  private static Action getInstance(String actionName) {
    switch (actionName) {
      case "upload":
        return new UploadAction();
      default:
        return null;
    }
  }
}

--Action to receive and process images

package com.example.action;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Base64;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

public class UploadAction extends Action {

  @Override
  protected String processRequest(HttpServletRequest request) {
    try {
      Part filePart = request.getPart("file");
      InputStream fileContent = filePart.getInputStream();
      byte[] byteArray = getByteArray(fileContent);
      String base64String = Base64.getEncoder().encodeToString(byteArray);

      System.out.println("filePart: " + filePart);
      System.out.println("fileContent: " + fileContent);
      System.out.println("byteArray: " + byteArray);
      System.out.println("base64String: " + base64String);

      request.setAttribute("image", base64String);
    } catch (Exception e) {}
    return "image.jsp";
  }

  private static byte[] getByteArray(InputStream is) throws Exception {
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    BufferedOutputStream os = new BufferedOutputStream(b);
    while (true) {
      int i = is.read();
      if (i == -1) break;
      os.write(i);
    }
    os.flush();
    os.close();
    return b.toByteArray();
  }
}

--Normal parameters are acquired by request.getParameter ("xxx "), but this time it is a file, so they are acquired by request.getPart ("xxx "). ――After that, I arrived at Base64 with the feeling of InputStream → byte → Base64. ――Since it's a big deal, I've made it up to the point where I pass the Base64 value to JSP and display it on the screen.

Image display

--JSP to display image

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<jsp:useBean id="image" scope="request" type="java.lang.String" />
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Java Sample</title>
  </header>
  <body>
    <h1>Hello</h1>
    <img src="data:image/png;base64,<%= image %>" />
  </body>
</html>

--Base64 can also be set in the src attribute of the img tag, so embed it. ――png It's not good to be decisive ――It seems that you can get it by server side processing, but it was not possible to use the method that came out immediately after google. ――If you can do so far, you can upload the image and the preview screen will be displayed.

Summary

--Even though you are using Servlet / JSP, the processing after receiving the file is pure Java, isn't it? --Servlet / JSP power has been wasted

Recommended Posts

[Java] Upload images and base64
This and that about Base64 (Java)
Java and JavaScript
XXE and Java
Java upload and download notes to Azure storage
[Beginner] Upload images and files with Spring [Self-satisfaction]
Upload and download notes in java on S3
Java enables extraction of PDF text and images
Getters and setters (Java)
CarrierWave Upload multiple images
[Java] Thread and Runnable
Java true and false
[Java] String comparison and && and ||
Java --Serialization and Deserialization
[Java] Arguments and parameters
[Java] Branch and repeat
[Java] Variables and types
java (classes and instances)
[Java] Overload and override
Study Java # 2 (\ mark and operator)
Java version 8 and later features
[Rails API + Vue] Upload and display images using Active Storage
[Java] Difference between == and equals
[Java] Stack area and static area
[Java] Generics classes and generics methods
Java programming (variables and data)
Java encryption and decryption PDF
How to minimize Java images
Save and display multiple images
Java class definition and instantiation
[Java] About String and StringBuilder
[Java] HashCode and equals overrides
☾ Java / Iterative statement and iterative control statement
Advantages and disadvantages of Java
java (conditional branching and repetition)
About Java Packages and imports
C # and Java Overrides Story
Java abstract methods and classes
Java while and for statements
Java encapsulation and getters and setters
Base64 encoder this and that
[Rails] How to upload images to AWS S3 using Carrierwave and fog-aws
Upload multiple images to Cloudinary on Active Storage and publish to Heroku
[Rails] How to upload images to AWS S3 using refile and refile-s3
About Java static and non-static methods
I compared PHP and Java constructors
Use java with MSYS and Cygwin
Distributed tracing with OpenCensus and Java
[Java] Difference between Hashmap and HashTable
Java variable declaration, initialization, and types
Java Excel Insertion and Image Extraction
Install Java and Tomcat with Ansible
AWS SDK for Java 1.11.x and 2.x
[Java] Basic types and instruction notes
Java release date and EOL summary
About fastqc of Biocontainers and Java
Java for beginners, expressions and operators 1
Java Primer Series (Variables and Types)
Encoding and Decoding example in Java
[Java beginner] About abstraction and interface
Upload a file using Java HttpURLConnection