Details of Java FileUploadUtil tool class

  • 2020-10-23 20:58:12
  • OfStack

Examples of this article for you to share the FileUploadUtil tool class specific code for your reference, the specific content is as follows


package com.gootrip.util;

import java.io.File;
import java.util.*;
import org.apache.commons.fileupload.*;
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;
import java.io.IOException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import java.util.regex.Matcher;

public class FileUploadUtil {

  // The temporary file location set when the upload limit is exceeded, note the absolute path 
  private String tempPath = null;

  // File upload target directory, note the absolute path 
  private String dstPath = null;

  // New file name, default to original file name when not set 
  private String newFileName = null;
  // Get the upload request 
  private HttpServletRequest fileuploadReq = null;

  // Sets the maximum amount of data allowed to be stored in memory , unit : Bytes. This parameter should not be set too large 
  private int sizeThreshold = 4096;

  // Sets the size of the file that allows the user to upload , unit : byte 
  // A total of 10M
  private long sizeMax = 10485760;

  // Picture file number 
  private int picSeqNo = 1;

  private boolean isSmallPic = false;

  public FileUploadUtil(){
  }

  public FileUploadUtil(String tempPath, String destinationPath){
    this.tempPath = tempPath;
    this.dstPath = destinationPath;
  }

  public FileUploadUtil(String tempPath, String destinationPath, HttpServletRequest fileuploadRequest){
    this.tempPath  = tempPath;
    this.dstPath = destinationPath;
    this.fileuploadReq = fileuploadRequest;
  }

  /**  File upload 
   * @return true  -  success; false  -  fail.
   */
  public boolean Upload(){
    DiskFileItemFactory factory = new DiskFileItemFactory();

    try {

      // If no destination directory is uploaded, it is created 
      FileUtil.makeDirectory(dstPath+"/ddd");
      /*if (!FileUtil.makeDirectory(dstPath+"/ddd")) {
        throw new IOException("Create destination Directory Error.");
      }*/
      // If there is no temporary directory, create it 
      FileUtil.makeDirectory(tempPath+"/ddd");
      /*if (!FileUtil.makeDirectory(tempPath+"/ddd")) {
        throw new IOException("Create Temp Directory Error.");
      }*/

      // Upload projects should be kept in memory as long as they are small enough. 
      // Larger items should be written to temporary files on the hard drive. 
      // Very large upload requests should be avoided. 
      // Limit the amount of space an item takes up in memory, limit the maximum upload request, and set the location of temporary files. 

      // Sets the maximum amount of data allowed to be stored in memory , unit : byte 
      factory.setSizeThreshold(sizeThreshold);
      // the location for saving data that is larger than getSizeThreshold()
      factory.setRepository(new File(tempPath));

      ServletFileUpload upload = new ServletFileUpload(factory);
      // Sets the size of the file that allows the user to upload , unit : byte 
      upload.setSizeMax(sizeMax);

      List fileItems = upload.parseRequest(fileuploadReq);
      // assume we know there are two files. The first file is a small
      // text file, the second is unknown and is written to a file on
      // the server
      Iterator iter = fileItems.iterator();

      //  Regular match, filter path to take filename 
      String regExp = ".+\\\\(.+)$";

      //  Type of file filtered out 
      String[] errorType = {".exe", ".com", ".cgi", ".asp", ".php", ".jsp"};
      Pattern p = Pattern.compile(regExp);
      while (iter.hasNext()) {
        System.out.println("++00++====="+newFileName);
        FileItem item = (FileItem) iter.next();
        // Ignore all other form information that is not a file field 
        if (!item.isFormField()) {
          String name = item.getName();
          System.out.println("++++====="+name);
          long size = item.getSize();
          // When there are multiple file fields, only those with files are uploaded 
          if ((name == null || name.equals("")) && size == 0)
            continue;
          Matcher m = p.matcher(name);
          boolean result = m.find();
          if (result) {
            for (int temp = 0; temp < errorType.length; temp++) {
              if (m.group(1).endsWith(errorType[temp])) {
                throw new IOException(name + ": Wrong File Type");
              }
            }
            String ext = "."+FileUtil.getTypePart(name);
            try {
              // Save the uploaded file to the specified directory 
              // When the file is uploaded to the database in the following article, this will be overridden 
              // Named after the original filename when no new filename is specified 
              if (newFileName == null || newFileName.trim().equals(""))
              {
                item.write(new File(dstPath +"/"+ m.group(1)));
              }
              else
              {
                String uploadfilename = "";
                if (isSmallPic)
                {
                  uploadfilename = dstPath +"/"+ newFileName+"_"+picSeqNo+"_small"+ext;
                }
                else
                {
                  uploadfilename = dstPath +"/"+ newFileName+"_"+picSeqNo+ext;
                }
                // Generate all ungenerated directories 
                System.out.println("++++====="+uploadfilename);
                FileUtil.makeDirectory(uploadfilename);
                //item.write(new File(dstPath +"/"+ newFileName));
                item.write(new File(uploadfilename));
              }
              picSeqNo++;
              //out.print(name + "&nbsp;&nbsp;" + size + "<br>");
            } catch (Exception e) {
              //out.println(e);
              throw new IOException(e.getMessage());
            }
          } else {
            throw new IOException("fail to upload");
          }
        }
      }
    } catch (IOException e) {
      System.out.println(e);
    } catch (FileUploadException e) {
      System.out.println(e);
    }
    return true;
  }

  /** Gets the individual file name from the path 
   * @author
   *
   * TODO  To change the template for this generated type comment, go to 
   *  window   -   preferences   -  Java  -   The code style   -   The code template 
   */
  public String GetFileName(String filepath)
  {
    String returnstr = "*.*";
    int length    = filepath.trim().length();

    filepath = filepath.replace('\\', '/');
    if(length >0)
    {
      int i = filepath.lastIndexOf("/");
      if (i >= 0)
      {
        filepath = filepath.substring(i + 1);
        returnstr = filepath;
      }
    }
    return returnstr;
  }
  /**
   *  Set up the temporary storage directory 
   */
  public void setTmpPath(String tmppath)
  {
    this.tempPath = tmppath;
  }
  /**
   *  Set target directory 
   */
  public void setDstPath(String dstpath) {
    this.dstPath = dstpath;
  }
  /**
   *  Sets the maximum number of bytes of uploaded file, default if not set 10M
   */
  public void setFileMaxSize(long maxsize) {
    this.sizeMax = maxsize;
  }
  /**
   *  Set up the Http  Request parameter, which is used to get file information 
   */
  public void setHttpReq(HttpServletRequest httpreq) {
    this.fileuploadReq = httpreq;
  }
  /**
   *  Set up the Http  Request parameter, which is used to get file information 
   */
  public void setNewFileName(String filename) {
    this.newFileName = filename;
  }

  /**
   *  Sets whether this upload file is a thumbnail file. This parameter is mainly used for thumbnail naming 
   */
  public void setIsSmalPic(boolean isSmallPic) {
    this.isSmallPic = isSmallPic;
  }

  /**
   *  Set up the Http  Request parameter, which is used to get file information 
   */
  public void setPicSeqNo(int seqNo) {
    this.picSeqNo = seqNo;
  }


}

Related articles: