Three Minutes Learn Java File Upload

Today, someone in the group happened to ask about Java file upload. Originally, this was the knowledge point inside Java, but my main focus now is on the JS part. But it's not a hassle anyway, I'll just post a post to talk about the basic implementation of Java file upload.

Say nothing but start.

The first step is to create a new blank web project. I still use eclipse as the development tool, but I don't like IDEAL.

Next, write index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Java File Upload</title>

Inside the body is a simple upload box. The uploaded server address is service/upload.jsp, which is also called upload.jsp in the service folder under the WebContent directory.

JSP is a Servlet, also known as a server program. It can be either a presentation layer or a service layer.


<h1>File Upload</h1>

<h1>File Upload</h1>
<form action="service/upload.jsp" method="post" enctype="multipart/form-data">
	<input type="file" name="file">
	<input type="submit" value="File Upload"> 

Next, import two jar packages, common-fileupload-1.2.jar ** and commons-io-2.0.1.jar.

The second step is to write the service class for file upload, which is also the server side. (I'm just writing JSP s and I'm too lazy to write Servlet s.)

Add a service folder to the WebContent directory and create a new upload.jsp inside.

To see the effect, we import another jar package that operates on JSON.

Then, on the JSP page, import the package:

<%@page import="org.apache.struts2.json.JSONUtil"%>
<%@page import=""%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@page import="java.text.DecimalFormat"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

Next, to write Java code on a JSP page, get a pair of angle brackets and the Java code will be written inside:



01. Get the true path to the file upload (where do you want to save the file in the project?)

//Get the exact directory where your files are uploaded, which is the real path to your web project
String realPath = request.getSession().getServletContext().getRealPath("/");
//Define uploaded directory
String dirPath = realPath+"/upload";
File dirFile = new File(dirPath);

02. Automatically create the path if it does not exist

//Automatically create uploaded directories

We place the uploaded file in the WebContent directory, which is a folder called upload under the project root path. If not, it is automatically created.

03. Upload operation, file name with UUID

//Upload operation  
FileItemFactory factory = new DiskFileItemFactory();  
ServletFileUpload upload = new ServletFileUpload(factory);  
String fileName = null;
HashMap<String,Object> map = new HashMap<String,Object>();
     List items = upload.parseRequest(request);
  if(null != items){  
         Iterator itr = items.iterator();  
             FileItem item = (FileItem);  
                fileName = UUID.randomUUID().toString()+getExt(item.getName());
		        //Directory where files are uploaded
                File savedFile = new File(dirPath,fileName);  
                map.put("name",item.getName());//Value Name of File
                map.put("size",item.getSize());//Real size of file
                map.put("sizeString",countFileSize(item.getSize()));//Get uppercase after file conversion
                map.put("url","upload/"+fileName);//Directory of the specific server that gets the file
}catch(Exception e){  

Finally, print the details of the file on the new page:


Auxiliary functions:

 * Convert file size to formatted string
public static String countFileSize(long fileSize) {
	String fileSizeString = "";
	try {
		DecimalFormat df = new DecimalFormat("#.00");
		long fileS = fileSize;
		if (fileS == 0) {
			fileSizeString = "0KB";
		} else if (fileS < 1024) {
			fileSizeString = df.format((double) fileS) + "B";
		} else if (fileS < 1048576) {
			fileSizeString = df.format((double) fileS / 1024) + "KB";
		} else if (fileS < 1073741824) {
			fileSizeString = df
					.format(((double) fileS / 1024 / 1024) - 0.01)
					+ "MB";
		} else {
			fileSizeString = df.format((double) fileS / 1024 / 1024 / 1024)
					+ "G";
	} catch (Exception e) {
	return fileSizeString;

 * Get the suffix of a file (with dots)
 * @param fileName
 *            file name
 * @return The suffix of the return file
public static String getExt(String fileName) {
	int pos = fileName.lastIndexOf(".");
	if (pos == -1)
		return "";
	return fileName.substring(pos, fileName.length());

 * Get the suffix of a file (without dots)
 * @param fileName
 *            file name
 * @return The suffix of the return file
public static String getExtNoPoint(String fileName) {
	if (fileName.lastIndexOf(".") == -1)
		return "";
	int pos = fileName.lastIndexOf(".") + 1;
	return fileName.substring(pos, fileName.length());

OK, now start the tomcat server.

No error was reported.

Because the welcome page is configured in web.xml, you can access it directly.


Upload a picture, click File Upload,

Wrong report, it still looks like jar package is missing.

The xwork-core- package is missing, which looks like both packages

There is a dependency, in fact, this is just to convert the file information into JSON format, if you have other useful jar packages, you can also, do not have to use these two jar packages.

Import it, restart tomcat, upload the file, OK.

Printed information:


Go to the Publishing Directory again

Sure enough, it creates an upload folder:

Pictures were also successfully uploaded~

Okay, this is the point here. As for the true path of the pictures, you generally want to save them in the database. I personally do not recommend that you save the pictures directly to the database by IO streaming. If the project is large, your database will run into hundreds of G s, which is a bit overwhelming. Still put the pictures on the hard disk. If you want to distribute them, try another way, such as that.ngix or something.

Tags: Java Eclipse Struts

Posted on Mon, 11 Oct 2021 12:02:51 -0400 by mubeena