Complete instance of file upload and download Tool class implemented by Java [Automatic naming of upload file]

  • 2020-11-18 06:16:07
  • OfStack

This article illustrates the file upload and download tool class implemented by Java. To share for your reference, the details are as follows:

This is a tool class that implements file upload and download using Java language under Eclipse environment. Like the C# file upload and download tool class 1 introduced earlier, in order to avoid duplication of file names in the server, the method of "server time (defined to milliseconds) + file name + file suffix" is adopted as the file name on the server during uploading. During the download process, spring mvc ResponseEntity is used to download the file. What is returned is the byte stream. After the download is successful, you can customize the save path of the file.

The specific source code is as follows:


package com.utils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
/**
 *  File upload download tool class 
 *
 */
public class FileHelper {
  /**
   *  Determine the directory based on the path, or create a directory if there is no directory 
   *
   * @param path
   */
  private static void createDir(String path) {
    File fileDir = new File(path);
    if (!fileDir.exists() && !fileDir.isDirectory()) {//  judge /download Whether the directory exists 
      fileDir.mkdir();//  Create a directory 
    }
  }
  /**
   *  Resolves the file name to the upload path of the file 
   *
   * @param fileName
   * @return  File name uploaded to server 
   */
  public static String transPath(String fileName, String path) {
    createDir(path);
    Date date = new Date();
    SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddhhmmssSSS");//  Define to milliseconds 
    String nowStr = dateformat.format(date);
    String filenameStr = fileName.substring(0, fileName.lastIndexOf("."));//  Remove filenames with suffixes 
    String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);//  The suffix 
    if (fileName.trim() != "") {//  If the name is not "", Indicates that the file exists, otherwise indicates that the file does not exist 
      path += "\\" + filenameStr + nowStr + "." + suffix;//  Define upload path 
    }
    return path;
  }
  /**
   *  Reminder file download 
   *
   * @param fileName
   * @param path
   * @return
   */
  public static ResponseEntity<byte[]> downloadFile(String fileName, String path) {
    try {
      fileName = new String(fileName.getBytes("GB2312"), "ISO_8859_1");//  Avoid filenames not showing in Chinese 
    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
    }
    File file = new File(path);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    headers.setContentDispositionFormData("attachment", fileName);
    ResponseEntity<byte[]> byteArr = null;
    try {
      byteArr = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return byteArr;
  }
  /**
   *  Writes data from the input stream to an array of bytes 
   *
   * @param in
   * @return
   */
  public static byte[] inputStream2ByteArray(InputStream in, boolean isClose) {
    byte[] byteArray = null;
    try {
      int total = in.available();
      byteArray = new byte[total];
      in.read(byteArray);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (isClose) {
        try {
          in.close();
        } catch (Exception e2) {
          System.out.println(" Close flow failure ");
        }
      }
    }
    return byteArray;
  }
}

For more information about java algorithm, please refer to Java Files and directories, Java Data Structure and Algorithm Tutorial, Java DOM Nodes and Java Caching techniques.

I hope this article has been helpful in java programming.


Related articles: