Java web file upload

File upload overview

File upload is actually the data interaction between Browser and server


Upload: we send the resources to be uploaded to the server and save them on the server. You need to upload photos to fill out a complete resume in Zhilian recruitment.

Download: when downloading a resource, the resource on the server is sent to the browser. For example, network hard disk! Is used to upload and download files.

Get resources from the server

In the process of uploading, the browser submits the file to the server in the form of stream. If you directly use Servlet to obtain the input stream of the uploaded file and then parse the request parameters, it is more troublesome. Therefore, you generally choose to use the file upload component of apache's open source tool common fileUpload. Common file upload depends on the common IO package, so you also need to download this package.

fileupload overview

fileupload is an upload component provided by the commons component of apache. Its main task is to help us parse request.getInputStream()

The JAR packages required by the fileupload component include:

commons-fileupload.jar, core package
commons-io.jar, dependent package


The core classes of fileupload include DiskFileItemFactory, ServletFileUpload and FileItem

The steps to use the fileupload component are as follows:

//1. Create a factory class DiskFileItemFactory object
DiskFileItemFactory factory = new DiskFileItemFactory();

//2. Create parser object using factory
ServletFileUpload fileUpload = new ServletFileUpload(factory);

//3. Use the parser to parse the request object
List<FileItem> list = fileUpload.parseRequest(request);

DiskFileItemFactory disk file item factory class

public DiskFileItemFactory(int sizeThreshold, File repository)
When constructing a factory, specify the memory buffer size and temporary file storage location

public void setSizeThreshold(int sizeThreshold)
Set the memory buffer size. The default is 10 K

public void setRepository(File repository)
Set the storage location of temporary files by default System.getProperty("java.io.tmpdir").

Memory buffer: when uploading a file, the contents of the uploaded file are stored in the memory buffer first. When the size of the uploaded file exceeds the size of the buffer, a temporary file will be generated on the server

Storage location of temporary files: temporary files generated by saving uploaded files that exceed the memory buffer size can be deleted through the delete() method of FileItem

FileItem

Represents each data part in the file upload form

Introduce the FileItem class, which is the final result we want. A FileItem object corresponds to a form item (form field). There are file fields and common fields in a form. You can use the isFormField() method of FileItem class to determine whether the form field is a common field. If it is not a common field, it is a file field


Note: because the file upload form adopts the encoding method of multipart / form data, which is different from the traditional url encoding, setCharacterEncoding() cannot be used in all getParameter() methods, and the problem of input item garbled cannot be solved

ServletFileUpload file upload core class

Construction of development environment







Configure Tomcat and download jar package

Common IO and common fileUpload packages

Maven Repository: commons-fileupload » commons-fileupload (mvnrepository.com)

Maven Repository: commons-io » commons-io (mvnrepository.com)


[note]: when using the IDEA package guide, you need to pay attention to the repair path and add lib to the project output directory

Realize file upload

Browser side

Front page:

File upload page upload.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
  <head>
    <title>File upload</title>
  </head>

  <body>
    <form action="${pageContext.request.contextPath}/servlet/UploadHandleServlet" enctype="multipart/form-data" method="post">
        Upload user:<input type="text" name="username"><br/>
        Upload file 1:<input type="file" name="file1"><br/>
        Upload file 2:<input type="file" name="file2"><br/>
        <input type="submit" value="Submit">
    </form>
  </body>
</html>
  1. There is only one way to interact with the file system in HTML: input type=file

  2. The enctype must be specified as multipart / form date so that the data can be segmented and uploaded correctly

    -enctype indicates the transmission format of data
    -Multpart / form date, which means that the data will be sent after segmented processing

  3. Multi file upload

    - to use the multiple attribute
    - background acceptance is an array

  4. The background needs to receive files by file type, not by string, and the responsible person will report an error;

  5. String path=request.getRealPath("/") is available in the background; Method to get the path of the project and put the file in the corresponding path.

Message prompt page message.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
  <head>
    <title>Message prompt</title>
  </head>

  <body>
        ${message}
  </body>
</html>

Server side

Servlet handling file upload

When the submitted form is a file upload form, there are also requirements for servlets.
First of all, we must be sure that the data of the file upload form is also encapsulated in the request object.

The request.getParameter(String) method obtains the character content of the specified form field, but the file upload form is no longer character content, but byte content, so it is invalid.

At this time, you can use the getInputStream() method of request to obtain the ServletInputStream object, which is a subclass of InputStream. This ServletInputStream object corresponds to the body of the whole form (from the first separation line to the last), which indicates that we need to analyze the data in the stream. Of course, parsing it is very troublesome, and Apache has provided us with a tool for parsing it: commons file upload

package me.gacl.web.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadHandleServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
                //Get the storage directory of the uploaded files, store the uploaded files in the WEB-INF directory, and do not allow direct access from the outside world to ensure the safety of the uploaded files
                String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");
                File file = new File(savePath);
                //Judge whether the saved directory of the uploaded file exists
                if (!file.exists() && !file.isDirectory()) {
                    System.out.println(savePath+"The directory does not exist and needs to be created");
                    //Create directory
                    file.mkdir();
                }
                //Message prompt
                String message = "";
                try{
                    //Using Apache file upload component to process file upload steps:
                    //1. Create a DiskFileItemFactory factory
                    DiskFileItemFactory factory = new DiskFileItemFactory();
                    //2. Create a file upload parser
                    ServletFileUpload upload = new ServletFileUpload(factory);
                     //Solve the Chinese garbled code of uploaded file name
                    upload.setHeaderEncoding("UTF-8");
                    //3. Judge whether the submitted data is the data of the uploaded form
                    if(!ServletFileUpload.isMultipartContent(request)){
                        //Get data in the traditional way
                        return;
                    }
                    //4. The servlet fileUpload parser is used to parse the uploaded data. The parsing result returns a list < FileItem > collection, and each FileItem corresponds to an input item of the Form
                    List<FileItem> list = upload.parseRequest(request);
                    for(FileItem item : list){
                        //If the fileitem encapsulates the data of ordinary input items
                        if(item.isFormField()){
                            String name = item.getFieldName();
                            //Solve the Chinese garbled code problem of data of common input items
                            String value = item.getString("UTF-8");
                            //value = new String(value.getBytes("iso8859-1"),"UTF-8");
                            System.out.println(name + "=" + value);
                        }else{//If the uploaded file is encapsulated in fileitem
                            //Get the name of the uploaded file,
                            String filename = item.getName();
                            System.out.println(filename);
                            if(filename==null || filename.trim().equals("")){
                                continue;
                            }
                            //Note: the file names submitted by different browsers are different. Some browsers submit file names with paths, such as c:\a\b .txt, while some are just simple file names, such as 1.txt
                            //Process the path part of the file name of the obtained uploaded file, and only keep the file name part
                            filename = filename.substring(filename.lastIndexOf("\\")+1);
                            //Get the input stream of the uploaded file in item
                            InputStream in = item.getInputStream();
                            //Create a file output stream
                            FileOutputStream out = new FileOutputStream(savePath + "\\" + filename);
                            //Create a buffer
                            byte buffer[] = new byte[1024];
                            //Identification to judge whether the data in the input stream has been read
                            int len = 0;
                            //The loop reads the input stream into the buffer, (len = in. Read (buffer)) > 0 indicates that there is data in the in
                            while((len=in.read(buffer))>0){
                                //Use the FileOutputStream output stream to write the buffer data to the specified directory (savePath + "\" + filename)
                                out.write(buffer, 0, len);
                            }
                            //Close input stream
                            in.close();
                            //Close output stream
                            out.close();
                            //Delete temporary files generated when processing file upload
                            item.delete();
                            message = "File upload succeeded!";
                        }
                    }
                }catch (Exception e) {
                    message= "File upload failed!";
                    e.printStackTrace();

                }
                request.setAttribute("message",message);
                request.getRequestDispatcher("/message.jsp").forward(request, response);
    }

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

        doGet(request, response);
    }
}

Register in the Web.xml file

<servlet>
    <servlet-name>UploadHandleServlet</servlet-name>
    <servlet-class>me.gacl.web.controller.UploadHandleServlet</servlet-class>
</servlet>

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

Operation effect


After the file is uploaded successfully, the uploaded file is saved in the upload directory under the WEB-INF directory, as shown in the following figure:

File upload tuning

Put the uploaded files in the WEB-INF directory

If the file uploaded by the user is not stored in the WEB-INF directory, the user can directly access the uploaded file through the browser, which is very dangerous.

If a user uploads an a.jsp file and then accesses the a.jsp file through the browser, the contents of the a.jsp will be executed. If there is the following statement in the a.jsp: Runtime.getRuntime().exec("shutdown – s – t 1");, Then you will

Usually, we will create an uploads directory in the WEB-INF directory to store uploaded files. To find this directory in the Servlet, we need to use the getRealPath(String) method of ServletContext. For example, in my upload1 project, there are the following statements:

ServletContext servletContext = this.getServletContext();
String savepath = servletContext.getRealPath("/WEB-INF/uploads");

Where savepath is: F:\tomcat6_1\webapps\upload1\WEB-INF\uploads.

Upload file with the same name (file rename)

Usually, we save the files uploaded by the user to the uploads directory, but what if the user uploads a file with the same name? This will lead to coverage. The way to deal with this problem is to use UUID to generate a unique name, and then use "" to connect the original name uploaded by the file

For example, the file uploaded by the user is "my one inch photo. jpg". After processing, the file name is "891b3881395f4175b969256a3f7b6e10# my one inch photo. jpg". This method will not cause the file to lose the extension, and because of the uniqueness of UUID, the uploaded file has the same name, but the problem of the same name will not occur on the server

public void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 request.setCharacterEncoding("utf-8");
 DiskFileItemFactory dfif = new DiskFileItemFactory();
 ServletFileUpload fileUpload = new ServletFileUpload(dfif);
 try {
 List<FileItem> list = fileUpload.parseRequest(request);
 //Get the second form item, because the first form item is username and the second is file
 FileItem fileItem = list.get(1);
 String name = fileItem.getName();//Get file name

 // If the client uses IE6, you need to get the file name from the full path
 int lastIndex = name.lastIndexOf("\\");
 if(lastIndex != -1) {
 name = name.substring(lastIndex + 1);
 }

 // Get the save directory of the uploaded file
 String savepath = this.getServletContext().getRealPath("/WEB-INF/uploads");
 String uuid = CommonUtils.uuid();//Generate uuid
 String filename = uuid + "_" + name;//The new file name is uuid + underline + original name

 //Create a file object and save the uploaded file to the path specified by the file
 //savepath, that is, the saving directory of the uploaded file
 //filename, file name
 File file = new File(savepath, filename);

 // Save file
 fileItem.write(file);
 } catch (Exception e) {
 throw new ServletException(e);
 } 
 }

One directory cannot store too many files (the storage directory is scattered)

A directory should not store too many files. Generally, 1000 files in a directory is the upper limit. If there are too many files, it will be "stuck" when opening the directory. You can try to print the C:\WINDOWS\system32 directory, and you will feel it

In other words, we need to put the uploaded files in different directories. However, you cannot create a directory for each uploaded file, which will lead to too many directories. So we should use some algorithm to "break up"!

There are many ways to break up, such as using dates to break up and generating a directory every day. You can also use the first letter of the file name to generate a directory, and the files with the same first letter are placed in the same directory.

Date scattering algorithm: if too many files are uploaded on a certain day, there will also be too many directory files;
Initial scattering algorithm: if the file name is Chinese, too many Chinese will lead to too many directories.

Here we use hash algorithm to break up:

Gets the name of the file hashCode: int hCode = name.hashCode()
obtain hCode The lower 4 bits of are then converted to hexadecimal characters
 obtain hCode Of 5~8 Bit and then converted to hexadecimal characters
 Use these two hexadecimal characters to generate a directory chain. For example, the lower 4 characters are "5"

The advantage of this algorithm is that a maximum of 16 directories are generated in the uploads directory, and a maximum of 16 directories are generated in each directory, that is, 256 directories. All uploaded files are placed in these 256 directories. If the maximum number of files per directory is 1000, a total of 256000 files can be saved

For example, if the name of the uploaded file is: new text document. txt, obtain the hash code of "new text document. txt", and then obtain the lower 4 bits and 58 bits of the hash code. If the lower 4 bits are 9 and the 58 bits are 1, the file saving path is uploads/9/1/

int hCode = name.hashCode();//Gets the hashCode of the file name
//Get the lower 4 bits of hCode and convert it to hexadecimal string
String dir1 = Integer.toHexString(hCode & 0xF);
//Get the lower 5 ~ 8 bits of hCode and convert it into hexadecimal string
String dir2 = Integer.toHexString(hCode >>> 4 & 0xF);
//Connect to the file save directory as a full path
savepath = savepath + "/" + dir1 + "/" + dir2;
//Because this path may not exist, create a File object and then create a directory chain to ensure that the directory already exists before saving the File
new File(savepath).mkdirs();

Size limit of single file uploaded

It's easy to limit the size of uploaded files. Just use the setFileSizeMax(long) of the ServletFileUpload class. The parameter is the maximum number of bytes of the uploaded file. For example, servletFileUpload.setFileSizeMax(1024*10) indicates that the maximum is 10KB.

Once the uploaded file exceeds the upper limit, a FileUploadBase.FileSizeLimitExceededException exception will be thrown. We can get this exception in the Servlet, and then output "the uploaded file exceeds the limit" to the page.

public void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 request.setCharacterEncoding("utf-8");
 DiskFileItemFactory dfif = new DiskFileItemFactory();
 ServletFileUpload fileUpload = new ServletFileUpload(dfif);
 // Set the upper limit of a single file uploaded to 10KB
 fileUpload.setFileSizeMax(1024 * 10);
 try {
 List<FileItem> list = fileUpload.parseRequest(request);
 //Get the second form item, because the first form item is username and the second is file
 FileItem fileItem = list.get(1);
 String name = fileItem.getName();//Get file name

 // If the client uses IE6, you need to get the file name from the full path
 int lastIndex = name.lastIndexOf("\\");
 if(lastIndex != -1) {
 name = name.substring(lastIndex + 1);
 }

 // Get the save directory of the uploaded file
 String savepath = this.getServletContext().getRealPath("/WEB-INF/uploads");
 String uuid = CommonUtils.uuid();//Generate uuid
 String filename = uuid + "_" + name;//The new file name is uuid + underline + original name

 int hCode = name.hashCode();//Gets the hashCode of the file name
 //Get the lower 4 bits of hCode and convert it to hexadecimal string
 String dir1 = Integer.toHexString(hCode & 0xF);
 //Get the lower 5 ~ 8 bits of hCode and convert it into hexadecimal string
 String dir2 = Integer.toHexString(hCode >>> 4 & 0xF);
 //Connect to the file save directory as a full path
 savepath = savepath + "/" + dir1 + "/" + dir2;
 //Because this path may not exist, create a File object and then create a directory chain to ensure that the directory already exists before saving the File
 new File(savepath).mkdirs();

 //Create a file object and save the uploaded file to the path specified by the file
 //savepath, that is, the saving directory of the uploaded file
 //filename, file name
 File file = new File(savepath, filename);

 // Save file
 fileItem.write(file);
 } catch (Exception e) {
 // Judge whether the type of exception thrown is FileUploadBase.FileSizeLimitExceededException
 // If yes, the limit is exceeded when uploading the file.
 if(e instanceof FileUploadBase.FileSizeLimitExceededException) {
 // Save error information in request
 request.setAttribute("msg", "Upload failed! The number of uploaded files exceeds 10 KB!");
 // Forward to the index.jsp page! You need to use ${msg} in the index.jsp page to display the error message
 request.getRequestDispatcher("/index.jsp").forward(request, response);
 return;
 }
 throw new ServletException(e);
 } 
}

Total size limit of uploaded files

Multiple files may be allowed to be uploaded in the form of uploading files, for example:


Sometimes we need to limit the size of a request. That is, the maximum number of bytes of the request (the sum of all form items)! This function is also very simple. You only need to call the setSizeMax(long) method of the ServletFileUpload class.

For example, fileUpload.setSizeMax(1024 * 10);, The maximum size for displaying the entire request is 10KB. When the request size exceeds 10KB, the parseRequest() method of ServletFileUpload class will throw FileUploadBase.SizeLimitExceededException.

Cache size and temporary directory

Let's think about it. If I upload a blu ray movie, first save the movie to memory, and then copy it to the server hard disk through memory, can your memory be consumed?
Therefore, it is impossible for the fileupload component to save all files in memory. fileupload will judge whether the file size exceeds 10KB. If so, save the file to the hard disk. If not, save it in memory.

10KB is the default value of fileupload. We can set it.

When a file is saved to the hard disk, fileupload saves the file to the system temporary directory. Of course, you can also set the temporary directory

public void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 request.setCharacterEncoding("utf-8");
 DiskFileItemFactory dfif = new DiskFileItemFactory(1024*20, new File("F:\\temp"));
 ServletFileUpload fileUpload = new ServletFileUpload(dfif);

 try {
 List<FileItem> list = fileUpload.parseRequest(request);
 FileItem fileItem = list.get(1);
 String name = fileItem.getName();
 String savepath = this.getServletContext().getRealPath("/WEB-INF/uploads");

 // Save file
 fileItem.write(path(savepath, name));
 } catch (Exception e) {
 throw new ServletException(e);
 } 
 }

 private File path(String savepath, String filename) {
 // Get file name from full path
 int lastIndex = filename.lastIndexOf("\\");
 if(lastIndex != -1) {
 filename = filename.substring(lastIndex + 1);
 }

 // Generate primary and secondary directories by file name
 int hCode = filename.hashCode();
 String dir1 = Integer.toHexString(hCode & 0xF);
 String dir2 = Integer.toHexString(hCode >>> 4 & 0xF);
 savepath = savepath + "/" + dir1 + "/" + dir2;
 // Create directory
 new File(savepath).mkdirs();

 // Prefix the file name with uuid
 String uuid = CommonUtils.uuid();
 filename = uuid + "_" + filename;

 // Create file completion path
 return new File(savepath, filename);
 }

To limit the types of uploaded files

When receiving the uploaded file name, judge whether the suffix is legal.

// Get the file name
                String uploadFileName = fileItem.getName();
                System.out.println("Uploaded file name: " + uploadFileName);
                if (uploadFileName.trim().equals("") || uploadFileName == null) {
                    continue;
                }

                // Get the uploaded file name / images/girl/paojie.png
                String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
                // Get the suffix of the file
                String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);

                /*
                 * If the file suffix fileExtName is not what we need, just press return. Do not process it and tell the user that the file type is wrong.
                 */

Improved UploadHandleServlet

package me.gacl.web.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

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

/**
* @ClassName: UploadHandleServlet
* @Description: TODO(The function of this class is described in one sentence)
* @author: Lonely Wolf
* @date: 2015-1-3 11:35:50 PM
*
*/
public class UploadHandleServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
                //Get the storage directory of the uploaded files, store the uploaded files in the WEB-INF directory, and do not allow direct access from the outside world to ensure the safety of the uploaded files
                String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");
                //Save directory of temporary files generated during upload
                String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
                File tmpFile = new File(tempPath);
                if (!tmpFile.exists()) {
                    //Create temporary directory
                    tmpFile.mkdir();
                }

                //Message prompt
                String message = "";
                try{
                    //Using Apache file upload component to process file upload steps:
                    //1. Create a DiskFileItemFactory factory
                    DiskFileItemFactory factory = new DiskFileItemFactory();
                    //Set the buffer size of the factory. When the uploaded file size exceeds the buffer size, a temporary file will be generated and stored in the specified temporary directory.
                    factory.setSizeThreshold(1024*100);//Set the size of the buffer to 100KB. If it is not specified, the default size of the buffer is 10KB
                    //Set the saving directory of temporary files generated during uploading
                    factory.setRepository(tmpFile);
                    //2. Create a file upload parser
                    ServletFileUpload upload = new ServletFileUpload(factory);
                    //Monitor file upload progress
                    upload.setProgressListener(new ProgressListener(){
                        public void update(long pBytesRead, long pContentLength, int arg2) {
                            System.out.println("File size:" + pContentLength + ",Currently processed:" + pBytesRead);
                            /**
                             * File size: 14608, currently processed: 4096
                                File size: 14608, currently processed: 7367
                                File size: 14608, currently processed: 11419
                                File size: 14608, currently processed: 14608
                             */
                        }
                    });
                     //Solve the Chinese garbled code of uploaded file name
                    upload.setHeaderEncoding("UTF-8");
                    //3. Judge whether the submitted data is the data of the uploaded form
                    if(!ServletFileUpload.isMultipartContent(request)){
                        //Get data in the traditional way
                        return;
                    }

                    //Set the maximum size of a single file to be uploaded. At present, it is set to 1024 * 1024 bytes, that is, 1MB
                    upload.setFileSizeMax(1024*1024);
                    //Set the maximum value of the total number of uploaded files. The maximum value = the sum of the maximum sizes of multiple files uploaded at the same time. At present, it is set to 10MB
                    upload.setSizeMax(1024*1024*10);
                    //4. The servlet fileUpload parser is used to parse the uploaded data. The parsing result returns a list < FileItem > collection, and each FileItem corresponds to an input item of the Form
                    List<FileItem> list = upload.parseRequest(request);
                    for(FileItem item : list){
                        //If the fileitem encapsulates the data of ordinary input items
                        if(item.isFormField()){
                            String name = item.getFieldName();
                            //Solve the Chinese garbled code problem of data of common input items
                            String value = item.getString("UTF-8");
                            //value = new String(value.getBytes("iso8859-1"),"UTF-8");
                            System.out.println(name + "=" + value);
                        }else{//If the uploaded file is encapsulated in fileitem
                            //Get the name of the uploaded file,
                            String filename = item.getName();
                            System.out.println(filename);
                            if(filename==null || filename.trim().equals("")){
                                continue;
                            }
                            //Note: the file names submitted by different browsers are different. Some browsers submit file names with paths, such as c:\a\b .txt, while some are just simple file names, such as 1.txt
                            //Process the path part of the file name of the obtained uploaded file, and only keep the file name part
                            filename = filename.substring(filename.lastIndexOf("\\")+1);
                            //Get the extension of the uploaded file
                            String fileExtName = filename.substring(filename.lastIndexOf(".")+1);
                            //If you need to limit the uploaded file type, you can judge whether the uploaded file type is legal through the file extension
                            System.out.println("The extension of the uploaded file is:"+fileExtName);
                            //Get the input stream of the uploaded file in item
                            InputStream in = item.getInputStream();
                            //Get the name of the file to save
                            String saveFilename = makeFileName(filename);
                            //Get the save directory of the file
                            String realSavePath = makePath(saveFilename, savePath);
                            //Create a file output stream
                            FileOutputStream out = new FileOutputStream(realSavePath + "\\" + saveFilename);
                            //Create a buffer
                            byte buffer[] = new byte[1024];
                            //Identification to judge whether the data in the input stream has been read
                            int len = 0;
                            //The loop reads the input stream into the buffer, (len = in. Read (buffer)) > 0 indicates that there is data in the in
                            while((len=in.read(buffer))>0){
                                //Use the FileOutputStream output stream to write the buffer data to the specified directory (savePath + "\" + filename)
                                out.write(buffer, 0, len);
                            }
                            //Close input stream
                            in.close();
                            //Close output stream
                            out.close();
                            //Delete temporary files generated when processing file upload
                            //item.delete();
                            message = "File upload succeeded!";
                        }
                    }
                }catch (FileUploadBase.FileSizeLimitExceededException e) {
                    e.printStackTrace();
                    request.setAttribute("message", "Single file exceeds maximum!!!");
                    request.getRequestDispatcher("/message.jsp").forward(request, response);
                    return;
                }catch (FileUploadBase.SizeLimitExceededException e) {
                    e.printStackTrace();
                    request.setAttribute("message", "The total size of uploaded files exceeds the maximum limit!!!");
                    request.getRequestDispatcher("/message.jsp").forward(request, response);
                    return;
                }catch (Exception e) {
                    message= "File upload failed!";
                    e.printStackTrace();
                }
                request.setAttribute("message",message);
                request.getRequestDispatcher("/message.jsp").forward(request, response);
    }

    /**
    * @Method: makeFileName
    * @Description: Generate the file name of the uploaded file. The file name is: uuid + "" + the original name of the file
    * @Anthor:Lonely Wolf
    * @param filename The original name of the file
    * @return uuid+"_"+The original name of the file
    */
    private String makeFileName(String filename){  //2.jpg
        //To prevent file overwriting, a unique file name should be generated for the uploaded file
        return UUID.randomUUID().toString() + "_" + filename;
    }

    /**
     * In order to prevent too many files under a directory, hash algorithm should be used to break up the storage
    * @Method: makePath
    * @Description:
    * @Anthor:Lonely Wolf
    *
    * @param filename File name, the storage directory should be generated according to the file name
    * @param savePath File storage path
    * @return New storage directory
    */
    private String makePath(String filename,String savePath){
        //Get the hashCode value of the file name, and get the address of the string object filename in memory
        int hashcode = filename.hashCode();
        int dir1 = hashcode&0xf;  //0--15
        int dir2 = (hashcode&0xf0)>>4;  //0-15
        //Construct a new save directory
        String dir = savePath + "\\" + dir1 + "\\" + dir2;  //upload\2\3  upload\3\5
        //File can represent either a file or a directory
        File file = new File(dir);
        //If the directory does not exist
        if(!file.exists()){
            //Create directory
            file.mkdirs();
        }
        return dir;
    }

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

        doGet(request, response);
    }
}

Tags: Java html

Posted on Wed, 08 Sep 2021 19:41:47 -0400 by mightyworld.com