[JAVA] Send and process form data to Servlet with FormData object and Commons File Upload

1. Purpose and specifications

  1. In Java Web application (Servlet, JSP), send the information (e.g. user name, password, image) entered in the form in JSP to the server (Servlet) by HTTP request.
  2. Check the input contents before sending the form, and do not send if there are any deficiencies. Therefore, dynamic processing is required
  3. Content-Type: In case of multipart / form-data Since request parameters cannot be acquired by Servlet, a method to acquire fields and files at the same time is required.
スクリーンショット 2018-12-29 17.48.21.png

2. Method

3. Environment and preparation

4. Implementation

sample.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE HTML>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Sample</title>
</head>
<body>
	<form id="form">
	Username : <input type="text" id="username" name="username"><br>
	Password : <input type="password" id="password" name="password"><br>
	Image :  <input type="file" id="image" name="image" accept="image/*"><br>
	<input type="submit" value="send">
	</form>
</body>
<script type="text/javascript" src="sample.js"></script>
</html>

sample.js


//Creating a form object
var form = document.getElementById("form");
//What to do when the submit event occurs
form.addEventListener("submit", function(event) {
	//Delete the default function of form and manage it with JavaScript
	event.preventDefault();
	check();
});

function check() {
	//Fetch the value of form
	var username = document.getElementById("username").value;
	var password = document.getElementById("password").value;
	var image = document.getElementById("image").value;

	//Send if entered
	if (username != "" && password != "" && image != "") {
		sendData();
	} else {
		alert("Please input all item.");
	}
}

function sendData() {
	//Creating a FormData object
	var formData = new FormData(form);
	//Send HTTP request with XMLHttpRequest
	var req = new XMLHttpRequest();

	//Processing when transmission / reception is completed
	req.addEventListener("load", function(event) {
		if (req.responseText == "done") {
			//Processing when processing is successful
			alert("Succeeded.");
		} else {
			alert("Failed to send.");
		}
	});
	//Processing when transmission / reception fails
	req.addEventListener("error", function(event) {
		alert("Error");
	});

	//HTTP request settings
	req.open("POST", "/sample/SampleServlet"); // /application name/Servlet name
	//Send request
	req.send(formData);
}

SampleServlet.java


package controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet("/SampleServlet")
public class SampleServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public SampleServlet() {
        super();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");

		//Response text
		String responseText = "done";

		//Create ServletFileUpload from DiskFileItemFactory
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload sfu = new ServletFileUpload(factory);

		try {
			//Store request form data in a list
			List list = sfu.parseRequest(request);
			for (Object o : list) {
				//Treat each form data as FileItem
				FileItem item = (FileItem) o;
				//Branch depending on whether FileItem is a field or a file
				if (item.isFormField()) {
					//For fields, get the field name and value
					// (In the form<input name="Field name" value="concents inputted")
					String fieldName = item.getFieldName();
					String value = item.getString();
					if (fieldName.equals("username")) {
						//Username processing
						System.out.println("username : " + value);
					} else if (fieldName.equals("password")){
						//Password processing
						System.out.println("password : " + value);
					}
				} else {
					File file = new File(item.getName());
					try {
						String dirPath = "Image file save destination";
						String filePath = dirPath + File.separator + file.getName();
						//Save image file
						item.write(new File(filePath));
					} catch (IOException e) {
						e.printStackTrace();
						responseText = "error";
					} catch (Exception e) {
						e.printStackTrace();
						responseText = "error";
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
			responseText = "error";
		}
		//Send response
		response.getWriter().print(responseText);
	}
}

6. Result

If not entered スクリーンショット 2018-12-29 17.49.27.png

When all items are entered スクリーンショット 2018-12-29 17.49.49.png

5. Reference

JavaScript

Servlet

Recommended Posts

Send and process form data to Servlet with FormData object and Commons File Upload
Form and process file and String data at the same time with Spring Boot + Java
How to achieve file upload with Feign
Android development-WEB access (POST) Try to communicate with the outside and send data. ~
I tried to implement file upload with Spring MVC
Create API to send and receive Json data in Spring