# 3.11 File Upload with getFile

File uploading is a common operation in web applications. In JFinal, this operation is made easy through the getFile series of methods provided by the Controller.

# Maven Dependency for File Upload

If you're planning to use file upload functionality in your JFinal application, it's necessary to include the cos dependency in your Maven project:

<dependency>
    <groupId>com.jfinal</groupId>
    <artifactId>cos</artifactId>
    <version>2022.2</version>
</dependency>
1
2
3
4
5

Note: Starting from JFinal version 4.9.18, support for uploading files larger than 2GB has been added. From this version onwards, you need to ensure you're using cos version 2022.2 or later. Earlier versions of JFinal are compatible with cos version 2020.4 and its predecessors.

# Using getFile

When dealing with file uploads in web forms, ensure that the form's encoding type is set to "multipart/form-data". This encoding type allows for the efficient transfer of file data:

<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="fileField">
    <input type="submit" value="Upload">
</form>
1
2
3
4

In your controller, you can retrieve the uploaded file using the getFile method:

public void upload() {
    // Get the uploaded file
    UploadFile file = getFile("fileField");
    
    // Now, you can process the uploaded file
    String fileName = file.getFileName();
    String filePath = file.getUploadPath();
    // ... and so on
}
1
2
3
4
5
6
7
8
9

Important Note: When handling multipart requests (where the form's encoding type is "multipart/form-data"), always call the getFile method before using any getPara methods. This is because multipart requests need to be parsed to extract both file and non-file data. The same principle applies when working with Interceptors and Validators.

# Configuring the Upload Path

By default, files are uploaded to an "upload" subdirectory located at the root of your project. This default path is referred to as the base upload path.

You can configure this path in the JFinalConfig.configConstant(Constants me) method using the setBaseUploadPath method:

public void configConstant(Constants me) {
    me.setBaseUploadPath("/custom/path");
}
1
2
3

The path specified can be either an absolute path (starting with a "/" or a drive letter on Windows) or a relative path (relative to the root of the project). Using an absolute path can be particularly useful when deploying multiple instances of an application on a single machine, allowing all instances to share a common directory for file uploads.

In summary, JFinal offers a streamlined approach to handling file uploads, allowing developers to focus on the logic of their applications rather than the intricacies of file handling.

Last Updated: 9/17/2023, 5:50:29 AM