SoFunction
Updated on 2025-03-02

Example of code transfer between File and MultipartFile in Java

1 Overview

When we are processing the function of file upload, we usually use the MultipartFile object to represent the uploaded file data. However, sometimes we may already have a File object instead of a MultipartFile object, which needs to be converted to a MultipartFile object for further processing.

In Java, the File object represents a reference to a file in the local file system, while the MultipartFile object is an interface provided by the Spring framework for handling file uploads. The MultipartFile interface provides many useful methods, such as getting file name, getting file content, getting file size, etc.

2 Code Examples

2.1 Introducing dependencies

<!--FilechangeMultipartFileneedtestBag-->
		<dependency>
			<groupId></groupId>
			<artifactId>spring-test</artifactId>
			<version>5.1.</version>
			<scope>compile</scope>
		</dependency>

2.2 MultipartFile to File

    public static File convert(MultipartFile file) throws IOException {
        File convFile = new File(());
        ();
        FileOutputStream fos = new FileOutputStream(convFile);
        (());
        ();
        return convFile;
    }

2.3 File to MultipartFile

//Convert to MultipartFile    private  MultipartFile getMulFileByPath(String filePath)
    {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        String textFieldName = "textField";
        int num = (".");
        String extFile = (num);
        FileItem item = (textFieldName, "text/plain", true,
                "MyFileName" + extFile);
        File newfile = new File(filePath);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try
        {
            FileInputStream fis = new FileInputStream(newfile);
            OutputStream os = ();
            while ((bytesRead = (buffer, 0, 8192))
                    != -1)
            {
                (buffer, 0, bytesRead);
            }
            ();
            ();
        }
        catch (IOException e)
        {
            ();
        }
 
        MultipartFile mfile = new CommonsMultipartFile(item);
        return mfile;
    }

Summarize

This is the article about the redirection between File and MultipartFile in Java. For more related contents of redirection between Java File and MultipartFile, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!