Thoroughly understand the MultipartFile interface and File class in Java

Foreword

Whether in projects or daily needs, we always have the need to operate file data. It is inevitable to use the File class to operate files in Java, and Spring provides us with an interface for operating files, through which we can obtain The file object uploaded by the user and written to the file system.

Article Directory

Preface

1. File class

2. MultipartFile interface

2.1 Source code and method functions

2.2 void transferTo(File dest)

Method body in CommonsMultipartFile

StandardMultipartHttpServletRequest implementation class

2.3 default void transferTo(Path dest)

Summarize

1. File class

java.io.File is a class in the Java standard library for manipulating file and directory paths. It provides many methods for operations such as creating, deleting, renaming, determining whether a file exists, and obtaining file information.

Get file information

  • boolean exists(): Determine whether the file or directory exists.
  • boolean isFile(): Determines whether it is a file.
  • boolean isDirectory(): Determines whether it is a directory.
  • String getName(): Get the name of the file or directory.
  • String getPath(): Get the path of a file or directory.
  • String getAbsolutePath(): Get the absolute path of a file or directory.
  • long length(): Get the size of the file (number of bytes).

File and directory operations

  • boolean createNewFile(): Create a new file. If the file already exists, it will not be created and false will be returned.
  • boolean mkdir(): Create a new directory. If the directory already exists, it will not be created and false will be returned.
  • boolean mkdirs(): Create a new directory and its parent directory if it does not exist.
  • boolean delete(): Delete a file or directory.

File path operations

  • boolean renameTo(File dest): Rename a file or directory. If successful, return true; otherwise, return false.
  • String[] list(): Returns an array of file and directory names in the directory.
  • File[] listFiles(): Returns an array of File objects for files and directories in the directory.

File filtering

  • String[] list(FilenameFilter filter): Returns an array of file and directory names in the directory that meet the specified filter conditions.
  • File[] listFiles(FileFilter filter): Returns an array of File objects for files and directories in the directory that meet the specified filter conditions.

2. MultipartFile interface

MultipartFile is an interface provided by the Spring framework, used to represent objects that handle file uploads. It is typically used to handle multipart/form-data type requests, such as forms that handle file uploads. First of all, we can still learn more about this interface through source code study.

2.1 Source code and method functions

public interface MultipartFile extends InputStreamSource {
    String getName();

    @Nullable
    String getOriginalFilename();

    @Nullable
    String getContentType();

    boolean isEmpty();

    long getSize();

    byte[] getBytes() throws IOException;

    InputStream getInputStream() throws IOException;

    default Resource getResource() {
        return new MultipartFileResource(this);
    }

    void transferTo(File dest) throws IOException, IllegalStateException;

    default void transferTo(Path dest) throws IOException, IllegalStateException {
        FileCopyUtils.copy(this.getInputStream(), Files.newOutputStream(dest));
    }
}
  • String getName(): Get the form field name of the uploaded file
  • String getOriginalFilename(): Get the original file name of the uploaded file
  • String getContentType(): Get the content type of the uploaded file
  • boolean isEmpty(): Determine whether the uploaded file is empty
  • long getSize(): Get the size of the uploaded file in bytes
  • byte[] getBytes() throws IOException: Get the byte array representation of the uploaded file
  • InputStream getInputStream() throws IOException: Get the input stream of the uploaded file
  • default Resource getResource() : Encapsulates MultipartFile into a Resource object, so that you can use the methods provided by the Resource interface to manipulate the contents of the uploaded file.
  • void transferTo(File dest) throws IOException, IllegalStateException: Save the uploaded file to the specified file;
  • default void transferTo(Path dest) throws IOException, IllegalStateException : Save the uploaded file in the specified path;

2.2 void transferTo(File dest)

We have already introduced that this method is an abstract method provided by Spring to save uploaded files to a specified file. Tracing the source code, we can see that this interface method is implemented by three implementation classes, namely CommonsMultipartFile, MockMultipartFile and StandardMultipartHttpServletRequest.

Method body in CommonsMultipartFile

We can see that the method body in CommonsMultipartFile mainly detects whether the incoming file is available and exists, and performs the writing operation after the detection is completed.

public void transferTo(File dest) throws IOException, IllegalStateException {
        if (!this.isAvailable()) {
            throw new IllegalStateException("File has already been moved - cannot be transferred again");
        } else if (dest.exists() & amp; & amp; !dest.delete()) {
            throw new IOException("Destination file [" + dest.getAbsolutePath() + "] already exists and could not be deleted");
        } else {
            try {
                this.fileItem.write(dest);
                LogFormatUtils.traceDebug(logger, (traceOn) -> {
                    String action = "transferred";
                    if (!this.fileItem.isInMemory()) {
                        action = this.isAvailable() ? "copied" : "moved";
                    }

                    return "Part '" + this.getName() + "', filename '" + this.getOriginalFilename() + "'" + (traceOn ? ", stored " + this .getStorageDescription() : "") + ": " + action + " to [" + dest.getAbsolutePath() + "]";
                });
            } catch (FileUploadException var3) {
                throw new IllegalStateException(var3.getMessage(), var3);
            } catch (IOException | IllegalStateException var4) {
                throw var4;
            } catch (Exception var5) {
                throw new IOException("File transfer failed", var5);
            }
        }
    }

There may be questions about this.isAvailable() in the above demo. We know that this here is actually the instantiation object of the class, but this.isAvailable() here is used to determine whether the destination file is available, and the class is called. Internal method, The condition for judging whether it is available is whether the target file is loaded into memory!

Here is an example of using this method. It should be noted that the method requires a target File object at this time. We need to create the target File object based on the target path when calling the target method.

//Get the original file name of the uploaded file
String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());

//Build the target file object
File destFile = new File("/path/to/destination/directory", originalFilename);

try {
    // Save the uploaded file to the target file
    file.transferTo(destFile);
    return "File uploaded successfully!";
} catch (IOException e) {
    e.printStackTrace();
    return "Failed to upload the file.";
}

StandardMultipartHttpServletRequest implementation class

The difference between another implementation class, StandardMultipartHttpServletRequest and CommonsMultipartFile, is that if you use StandardMultipartHttpServletRequest to directly upload files, there may be a directory jump problem, but CommonsMultipartFile will not. This is because it has relevant restrictions on the path separator. You can check the specific part. Take a look at this blog: https://www.cnblogs.com/zpchcbd/p/17148291.html The implementation class of MockMultipartFile is even simpler. It makes a simple copy of the input and output streams, so there is no need to mention the word count here. .

2.3 default void transferTo(Path dest)

This default method has been rewritten in the implementation class, but the main function remains the same, which is to write the uploaded file into the Path object of the specified path to implement the file upload function.

Here is the sample code used:

//Build target file path
String uploadDirectory = "/path/to/destination/directory";
String originalFilename = file.getOriginalFilename();
Path filePath = Paths.get(uploadDirectory, originalFilename);

try {
// Save the uploaded file to the target file
    file.transferTo(filePath);
    return "File uploaded successfully!";
} catch (IOException e) {
    e.printStackTrace();
    return "Failed to upload the file.";
}

Summary

This article mainly focuses on sorting out the functions of the MultipartFile interface and related methods in the File class. It focuses on analyzing the file writing to the File object and the Path object. For specific knowledge about file management, you can pay attention to the subsequent Litchi review. SpringBoot integrates MinIO’s blog and subsequent blog output. I hope it can help those in need~~~

Today has become the past, but we still look forward to the future tomorrow! I am Litchi, and I will accompany you on the road of technological growth~~~

If the blog post is helpful to you, you can give Lizhi three clicks. Your support and encouragement are Lizhi’s biggest motivation!

If the content of the blog post is incorrect, you are also welcome to criticize and correct it in the comment area below! ! !