A simple example of uploading large files with fileupload component

  • 2021-10-27 08:27:19
  • OfStack

1. FileUploadServlet. java file to realize upload processing


import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
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.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadServlet extends HttpServlet
{
 private static final long serialVersionUID = 1L;

 public FileUploadServlet()
 {
 super();
 }

 protected void doGet(HttpServletRequest request,
 HttpServletResponse response) throws ServletException, IOException
 {
 this.doPost(request, response);
 }

 protected void doPost(HttpServletRequest request,
 HttpServletResponse response) throws ServletException, IOException
 {

 final long MAX_SIZE = 2048 * 1024 * 1024;//  Set the maximum value of uploaded files to 2G Can be changed to be larger 
 //  List of file formats allowed to upload 
 final String[] allowedExt = new String[]
 { "exe","jpg","DT" };
 response.setContentType("text/html");
 //  Set the character encoding to UTF-8,  Unified 1 Coding and processing of garbled codes 
 response.setCharacterEncoding("UTF-8");

 //  Instantiation 1 Hard disk file factory , Used to configure upload components ServletFileUpload
 DiskFileItemFactory dfif = new DiskFileItemFactory();

 //  Instantiate the upload component with the above factory 
 ServletFileUpload sfu = new ServletFileUpload(dfif);
 //  Set the maximum upload size 
 sfu.setSizeMax(MAX_SIZE);

 PrintWriter out = response.getWriter();
 //  From request Get a list of all uploaded domains 
 List fileList = null;
 try
 {
 fileList = sfu.parseRequest(request);
 } catch (FileUploadException e)
 {//  Handling Excessive File Size Exception 
 if (e instanceof SizeLimitExceededException)
 {
 out.println(" File size exceeds specified size :" + MAX_SIZE + " Byte <p />");
 out.println("<a href=\"FileUpload.html\" target=\"_top\"> Return </a>");
 return;
 }
 e.printStackTrace();
 }
 //  No files uploaded 
 if (fileList == null || fileList.size() == 0)
 {
 out.println(" Please select Upload File <p />");
 out.println("<a href=\"FileUpload.html\" target=\"_top\"> Return </a>");
 return;
 }
 // File size takes two decimal places 
 DecimalFormat digit=new DecimalFormat("0.00");
 //  Get all uploaded files 
 Iterator fileItr = fileList.iterator();
 //  Loop through all files 
 while (fileItr.hasNext())
 {
 FileItem fileItem = null;
 String path = null;
 double size = 0;
 //  Get the current file 
 fileItem = (FileItem) fileItr.next();
 //  Ignore simplicity form Field instead of the file field of the upload field (<input type="text" /> Etc )
 if (fileItem == null || fileItem.isFormField())
 {
 continue;
 }

 //  Get the size of the file, K Units and keep two decimal places 
 size = (double)fileItem.getSize()/1024;
 if ("".equals(path) || size == 0)
 {
 out.println("<html><head><title> Upload processing interface </title></head>");
 out.println(" Please select Upload File <p />");
 out.println("<a href=\"FileUpload.html\" target=\"_top\"> Return </a>");
 out.println("</html>");
 return;
 }
 //  Get the full path of the file 
 path = fileItem.getName();
  
 //  Get the filename of the stripped path 
 String t_name = path.substring(path.lastIndexOf("\\") + 1);
 //  Get the file extension ( You will get the full name without extension )
 String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
 //  Refuse to accept file types other than the specified file format 
 int allowFlag = 0;
 int allowedExtCount = allowedExt.length;
 for (; allowFlag < allowedExtCount; allowFlag++)
 {
 if (allowedExt[allowFlag].equals(t_ext))
 break;
 }
 if (allowFlag == allowedExtCount)
 {
 out.println("<html><head><title> Upload processing interface </title></head>");
 out.println(" Please upload the following types of files <p />");
 for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)
 out.println("*." + allowedExt[allowFlag]
 + "&nbsp;&nbsp;&nbsp;");
 out.println("<p /><a href=\"FileUpload.html\" target=\"_top\"> Return </a>");
 out.println("</html>");
 return;
 }
 try
 {
 //  Save the file to the server root directory 
 fileItem.write(new File("\\"+t_name));
 System.out.println(t_name);
 out.println("<html><head><title> Upload processing interface </title></head>");
 out.println(" The name of the file is: " + path + "<br>");
 out.println(" The file was uploaded successfully,   Saved as : " + t_name
 + "<br>"+"  File size : " + digit.format(size) + "K <p />");
 out.println("<a href=\"FileUpload.html\" target=\"_top\"> Continue uploading </a>");
 out.println("</html>");
 } catch (Exception e)
 {
 e.printStackTrace();
 }
 }
 }
}

2. FileUpload. html file to upload pages.


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title> File upload </title>
</head>
<body>
<form action="FileUploadServlet" method="post"
enctype="multipart/form-data">
<input type="file" size="30"
name="file01" /><br>
<pre> <input name="submit" type="submit" value=" Upload "> <input name="reset" type="reset" value=" Reset ">
</pre>
</form>
</body>
</html>

3. Configure servlet and filter in web. xml file. The filter solves the garbled code when the uploaded file name is Chinese.


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<display-name>FileUploadServlet</display-name>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>FileUploadServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/FileUploadServlet</url-pattern>
</servlet-mapping>

<filter>
<filter-name>setCharacterEncoding </filter-name>
<filter-class>com.xulu.EncodingChange</filter-class>
<init-param>
<param-name>ignore </param-name>
<param-value>true </param-value>
</init-param>

<init-param>
<param-name>encoding </param-name>
<param-value>UTF-8 </param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>setCharacterEncoding </filter-name>
<url-pattern>/* </url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
</web-app>

4. The filter files EncodingChange. java and setCharacterEncoding. java are as follows, respectively, and place their compiled. class files in the WEB-INF\ classes\ com\ xulu folder under the root directory


package com.xulu;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EncodingChange implements Filter
{
 protected String encoding = null;
 protected FilterConfig filterconfig = null;
 protected boolean ignore = true;

 public void destroy()
 {
 this.encoding = null;
 this.filterconfig = null;
 }

 public void doFilter(ServletRequest requests, ServletResponse responses,
 FilterChain chain) throws IOException, ServletException
 {
 // TODO Auto-generated method stub
 HttpServletRequest request = (HttpServletRequest) requests;
 HttpServletResponse response = (HttpServletResponse) responses;
 if (ignore || request.getCharacterEncoding() == null)
 {
 String encoding = selectEncoding(request);
 if (encoding != null)
 {
 request.setCharacterEncoding(encoding);
 request.getSession().getAttribute("Login_Student");
 request.getSession().getAttribute("Login_Teacher");
 request.getSession().getAttribute("Login_Admin");
 }
 }
 chain.doFilter(request, response);
 }

 public void init(FilterConfig filterconfig) throws ServletException
 {
 // TODO Auto-generated method stub
 this.filterconfig = filterconfig;
 this.encoding = filterconfig.getInitParameter("encoding");
 String value = filterconfig.getInitParameter("ignore");
 if (value == null)
 {
 this.ignore = true;
 } else if (value.equalsIgnoreCase("true"))
 {
 this.ignore = true;
 } else if (value.equalsIgnoreCase("yes"))
 {
 this.ignore = true;
 } else
 {
 this.ignore = false;
 }
 }

 public String selectEncoding(ServletRequest request)
 {
 return this.encoding;
 }
}
 And 
package com.xulu;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class setCharacterEncoding implements Filter{
protected String encoding=null;
protected FilterConfig filterconfig=null;
protected boolean ignore=true;


public void destroy() {
this.encoding=null;
this.filterconfig=null;
}

public void doFilter(ServletRequest requests, ServletResponse responses,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest request=(HttpServletRequest)requests;
HttpServletResponse response=(HttpServletResponse)responses;
if(ignore||request.getCharacterEncoding()==null){
String encoding=selectEncoding(request);
if(encoding!=null){
request.setCharacterEncoding(encoding);
request.getSession().getAttribute("Login_Student");
request.getSession().getAttribute("Login_Teacher");
request.getSession().getAttribute("Login_Admin");
}
}
chain.doFilter(request, response);
}

public void init(FilterConfig filterconfig) throws ServletException {
// TODO Auto-generated method stub
this.filterconfig = filterconfig;
this.encoding = filterconfig.getInitParameter("encoding");
String value = filterconfig.getInitParameter("ignore");
if (value == null) {
this.ignore = true;
} else if (value.equalsIgnoreCase("true")) {
this.ignore = true;
} else if (value.equalsIgnoreCase("yes")) {
this.ignore = true;
} else {
this.ignore = false;
}
}
public String selectEncoding(ServletRequest request){
return this.encoding;
}
}

5. You can upload the page in the browser, and just visit http://localhost: 8080/**/FileUpload.html. Among them, ** named web folder for yourself, such as DoUpload, all the files above are in this directory, and DoUpload folder is placed under webapp folder of Tomcat.

Add: Before all the above steps, three. jar files, commons-fileupload-1. 2.1. jar, commons-io-1. 4. jar and servlet-api. jar can be downloaded online


Related articles: