java files are asynchronously uploaded based on servlet

  • 2020-05-12 02:38:38
  • OfStack

Here we use the servlet-based file upload asynchronously, so let's cut the crap and go straight to the code...


package com.future.zfs.util;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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;

@SuppressWarnings("serial")
public class FileUploadServlet extends HttpServlet {

  final long MAX_SIZE = 10 * 1024 * 1024;//  Set the maximum size of the uploaded file  10M
  //  A list of file formats that are allowed to be uploaded 
  final String[] allowtype = new String[] {"jpg","jpeg","gif","txt","doc","docx","mp3","wma","m4a","xls"};

  public FileUploadServlet() {
    super();
  }

  public void destroy() {
    super.destroy(); 
  }

  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    //  Set the character encoding to UTF-8,  This supports the display of Chinese characters 
    response.setCharacterEncoding("UTF-8");

    //  instantiation 1 Hard disk file factory , Used to configure the upload component ServletFileUpload
    DiskFileItemFactory dfif = new DiskFileItemFactory();
    dfif.setSizeThreshold(4096);//  Set the size of memory used to temporarily store files when uploading files , Here is the 4K. Any excess will be temporarily stored on the hard disk 
    dfif.setRepository(new File(request.getRealPath("/")
        + "uploadtemp"));//  Sets the directory where temporary files are stored ,web In the root directory uploadtemp directory 
    //  Instantiate the upload component with the factory above 
    ServletFileUpload sfu = new ServletFileUpload(dfif);
    //  Set the maximum upload size 
    sfu.setSizeMax(MAX_SIZE);

    PrintWriter out = response.getWriter();
    //  from request get   all   Upload a list of domains 
    List fileList = null;
    try {
      fileList = sfu.parseRequest(request);
    } catch (FileUploadException e) {//  Handle file size exceptions 
      if (e instanceof SizeLimitExceededException) {
        out.println("{message:' The file size exceeds the specified size :"+MAX_SIZE+" byte '}");
        return;
      }
      e.printStackTrace();
    }
    //  No file uploaded 
    if (fileList == null || fileList.size() == 0) {
      out.println("{message:' Please select upload file '}");
      return;
    }
    //  Get all the uploaded files 
    Iterator fileItr = fileList.iterator();
    //  Loop through all files 
    while (fileItr.hasNext()) {
      FileItem fileItem = null;
      String path = null;
      long size = 0;
      //  Get the current file 
      fileItem = (FileItem) fileItr.next();
      //  Ignore the simple form Field instead of the file field of the upload domain (<input type="text" /> Etc. )
      if (fileItem == null || fileItem.isFormField()) {
        continue;
      }
      //  Get the full path to the file 
      path = fileItem.getName();
      //  Get the size of the file 
      size = fileItem.getSize();
      if ("".equals(path) || size == 0) {
        out.println("{message:' Please select upload file '}");
        return;
      }

      //  Gets the file name that removes the path 
      String t_name = path.substring(path.lastIndexOf("\\") + 1);
      //  Gets the file's extension ( You get the full name without an extension )
      String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
      //  Refuse to accept a file type other than the specified file format 
      int allowFlag = 0;
      int allowedExtCount = allowtype.length;
      for (; allowFlag < allowedExtCount; allowFlag++) {
        if (allowtype[allowFlag].equals(t_ext))
          break;
      }
      if (allowFlag == allowedExtCount) {
        String message = "";
        for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++){
          message+="*." + allowtype[allowFlag]
                        + " ";
        }
        out.println("{message:' Please upload the following types of files "+message+"'}");
        return;
      }

      long now = System.currentTimeMillis();
      //  Generate the file name saved after uploading according to system time 
      String prefix = String.valueOf(now);
      //  Save the full path to the final file , Stored in the web In the root directory upload directory 
      String u_name = request.getRealPath("/") + "upload/"
          + prefix + "." + t_ext;
      // Original file name 
      path=request.getRealPath("/") + "upload/"+path;
      try {
        //  Save the file 
        fileItem.write(new File(path));
        response.setStatus(200);
        out.println("{message:\" File uploaded successfully .  Has been saved as a : " + prefix + "." + t_ext
            + "  The file size : " + size + " byte \"}");
      } catch (Exception e) {
        e.printStackTrace();
      }

    }
  }
}

web.xml


<servlet>
    <servlet-name>fileUploadServlet</servlet-name>
    <servlet-class>com.future.zfs.util.FileUploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>fileUploadServlet</servlet-name>
    <url-pattern>/fileUploadServlet</url-pattern>
  </servlet-mapping>

The upload page


<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/ajaxfileupload.js"></script>
    <script type="text/javascript">
  function ajaxFileUpload()
  {
    
    $("#loading")
    .ajaxStart(function(){
      $(this).show();
    })// Displays when the file is uploaded 1 A picture 
    .ajaxComplete(function(){
      $(this).hide();
    });// File upload is complete to hide the image 
    
    $.ajaxFileUpload
    (
      {
        url:'fileUploadServlet',// The server-side request address for file upload 
        secureuri:false,//1 A set to false
        fileElementId:'file',// File upload space id attribute  <input type="file" id="file" name="file" />
        dataType: 'json',// Return value type  1 A set to json
        success: function (data, status) // The server successfully responds to the handler 
        {
          //alert(data.message);// Returned from the server json Remove the message The data in the , Among them message For in struts2 Is a member variable defined in 
          $('#myspan').html(data.message);
          if(typeof(data.error) != 'undefined')
          {
            if(data.error != '')
            {
              //alert(data.error);
              $('#myspan').html(data.message);
            }else
            {
              //alert(data.message);
              $('#myspan').html(data.message);
            }
          }
        },
        error: function (data, status, e)// The server responds to the failure handler 
        {
          //alert(e);
          $('#myspan').html(e);
        }
      }
    )
    
    return false;

  }
  </script>
  </head>
  <body>
    <img src="images/loading.gif" id="loading" style="display: none;">
    <span style="color: red;" id="myspan"></span><br/>
    <input type="file" id="file" name="file" />
    <br />
    <input type="button" value=" upload " onclick="return ajaxFileUpload();">
    <a href="fileDownLoadServlet?filename= The address book .xls"> Haha, test file download </a>
  </body>
</html>

It is important to note that response.setContentType ("text/html") should be set when using ajaxFileUpload to upload based on servlet. response.setContentType("text/html"), although dataType: 'json' is set to json; Otherwise, the data returned by the server will not be retrieved and a dialog box will pop up.


Related articles: