The difference between the properties of MultipartFile file.getOriginalFilename() and file.getName() MultipartFile and File interchange

MultipartFile

I. Overview

MultipartFile is a class under the org.springframework.web.mutipart package, which means that if you want to use the MultipartFile class, you must introduce the spring framework. In other words, if you want to use the MultipartFile class in the project, then the project must use spring Only the framework, otherwise this class cannot be introduced.

The following is based on the spring-web.5.2.9.RELEASE source code to understand the MultipartFile
insert image description here
MultipartFile annotation description

The first sentence: A representative form that can receive uploaded files using multiple request methods. In other words, if you want to use the spring framework to implement the file upload function in the project, MultipartFile may be the most suitable choice, and the various request methods mentioned here can be commonly understood as submitting in the form of a form.
The second sentence: The content of this file can be stored in memory or in a temporary location on disk.
The third sentence: No matter what happens, the user is free to copy the file content to the session storage, or store it in a form of permanent storage, if necessary.
Fourth sentence: This temporary storage will be cleared after the request ends.

2. Common methods of MultipartFile

First of all, MultipartFile is an interface and inherits from InputStreamSource, and the getInputStream method is encapsulated in the InputStreamSource interface. The return type of this method is InputStream type, which is why MultipartFile files can be converted into input streams. The file in MultipartFile format can be converted into an input stream by the following code.

multipartFile.getInputStream();
method illustrate
String getName() Return the name of the parameter, such as (MultipartFile oriFile), return as oriFile
String getOriginalFilename() Returns the original filename in the client's file system. 这可能包含盘符路径信息,具体取决于所使用的浏览器, 解决方法可参考 link
String getContentType() The getContentType method obtains the type of the file. Note that it is the type of the file, not the extension of the file.
boolean isEmpty() Determine whether the incoming file is empty, if it is empty, it means that no file has been passed in.
long getSize() Used to get the size of the file in bytes.
byte[] getBytes() It is used to convert the file into a byte array for transmission, and an IOException will be thrown.
InputStream getInputStream() Returns an InputStream to read the contents of the file from. Through this method, the stream can be obtained
Resource getResource()
void transferTo(File dest) Write the received file to the destination file, 如果目的文件已经存在了则会先进行删除. Used to convert MultipartFile to File type file
void transferTo(Path dest) Transfer the received file to the given destination file. The default implementation only copies the file input stream.
@GetMapping("/uploadFile")
public ApiResult test(@RequestParam MultipartFile uploadFile) throws IOException {
    
    
	// 原文件名称
    System.out.println("uploadFile.getOriginalFilename() = " + uploadFile.getOriginalFilename());
    // 文件的接收参数 @RequestParam MultipartFile uploadFile中的 uploadFile
    System.out.println("uploadFile.getName() = " + uploadFile.getName());
    // 文件的类型
    System.out.println("uploadFile.getContentType() = " + uploadFile.getContentType());
    System.out.println("uploadFile.getResource() = " + uploadFile.getResource());
    System.out.println("uploadFile.getBytes() = " + uploadFile.getBytes());
    // 文件大小
    System.out.println("uploadFile.getSize() = " + uploadFile.getSize());
    return ApiResult.ok();
}

Uploaded file: a.png
insert image description here
Execution result:

uploadFile.getOriginalFilename() = a.png
uploadFile.getName() = uploadFile
uploadFile.getContentType() = image/jpeg
uploadFile.getResource() = MultipartFile resource [file]
uploadFile.getBytes() = [B@1fa8cd72
uploadFile.getSize() = 143

3. The use of Springboot and MultipartFile

3.1 Set file upload size limit

The default file upload size of springboot is 1M. If it exceeds 1M, an exception will be thrown, as follows:

org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.
	at org.apache.tomcat.util.http.fileupload.FileUploadBase$FileItemIteratorImpl$FileItemStreamImpl$1.raiseError(FileUploadBase.java:628) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.checkLimit(LimitedInputStream.java:76) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.read(LimitedInputStream.java:135) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
	at java.io.FilterInputStream.read(Unknown Source) ~[na:1.8.0_131]
	at org.apache.tomcat.util.http.fileupload.util.Streams.copy(Streams.java:98) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.tomcat.util.http.fileupload.util.Streams.copy(Streams.java:68) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:293) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.catalina.connector.Request.parseParts(Request.java:2902) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.catalina.connector.Request.parseParameters(Request.java:3242) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.catalina.connector.Request.getParameter(Request.java:1136) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.catalina.connector.RequestFacade.getParameter(RequestFacade.java:381) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:84) ~[spring-web-4.3.19.RELEASE.jar:4.3.19.RELEASE]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.19.RELEASE.jar:4.3.19.RELEASE]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.19.RELEASE.jar:4.3.19.RELEASE]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.19.RELEASE.jar:4.3.19.RELEASE]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) [tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806) [tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) [tomcat-embed-core-8.5.34.jar:8.5.34]
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.34.jar:8.5.34]
	at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_131]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_131]
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.34.jar:8.5.34]
	at java.lang.Thread.run(Unknown Source) [na:1.8.0_131]

method one

application.properties configuration file

# 上传的单个文件的大小最大为3MB
spring.servlet.multipart.max-file-size = 3MB
# 单次请求的所有文件的总大小最大为9MB
spring.servlet.multipart.max-request-size = 9MB

# 如果是想要不限制文件上传的大小,那么就把两个值都设置为-1

way two

Configure the MultipartConfigElement method in the configuration class, and register the configuration class in the container, code example:

@Configuration
@SpringBootApplication
@MapperScan("com.demo.explain.mapper")
public class StoreApplication {
    
    
 
	public static void main(String[] args) {
    
    
		SpringApplication.run(StoreApplication.class, args);
	}
	@Bean
	public MultipartConfigElement getMultipartConfigElement() {
    
    
		MultipartConfigFactory factory = new MultipartConfigFactory();
		// DataSize dataSize = DataSize.ofMegabytes(10);
		// 设置文件最大10M,DataUnit提供5中类型B,KB,MB,GB,TB
		factory.setMaxFileSize(DataSize.of(10, DataUnit.MEGABYTES));
		factory.setMaxRequestSize(DataSize.of(10, DataUnit.MEGABYTES));
		// 设置总上传数据总大小10M
		return factory.createMultipartConfig();
	}
}

global exception catch

package com.example.demo.config;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

// 全局异常捕获类
@ControllerAdvice
public class GlobalExceptionHandler {
    
    

    // 若上传的文件大小超过配置类中配置的指定大小后会触发下面的异常
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public void defultExcepitonHandler(MaxUploadSizeExceededException ex) {
    
    
		log.info("[exceptionHandler] maxUploadSizeExceededExceptionHandler :"+e.getMessage(),e);
		return ResponseFactory.build(900001,"文件大小超过限制");
    }
}

3.2 Springboot uploads a single file, including other parameters

The Controller layer code is as follows:

@RestController
@RequestMapping("/test")
public class MultipartFileController {
    
    
    @PostMapping("/upload")
    public String multipartFileTest(@ApiParam(value = "multipartFile") @RequestParam MultipartFile multipartFile,@ApiParam(value = "用户名") @RequestParam  String userName) throws Exception{
    
    
       
        return "成功";
    }
}

Postman passes parameters as follows:
insert image description here

In the request body, the from-data method should be selected first; the multipartFile in the key should be consistent with the variable name of the backend interface, and the type should be File.

3.3 Springboot uploads multiple files, including the request body

The Controller layer code is as follows: the request body needs to be annotated with @Valid instead of @RequestBody

@RestController
@RequestMapping("/test")
public class MultipartFileController {
    
    
    @PostMapping("/upload")
    public String multipartFileTest(@ApiParam(value = "multipartFiles") @RequestParam MultipartFile[] multipartFiles,@Valid UserDO userDO) throws Exception{
    
    
       
        return "成功";
    }
}
import lombok.Data;

@Data
public class UserDO {
    
    
    private String userName;
    private String email;
    private int age;

Postman passes parameters as follows:
insert image description here

4. Pit of transferTo method in MultipartFile

4.1 After calling the transferTo() method, when the file.getInputStream() method is obtained again, a temporary file exception is reported

2023-02-06 10:00:20.557 ERROR 14780 --- [http-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception

java.io.FileNotFoundException: C:\Users\AppData\Local\Temp\work\demo\upload_file.tmp (系统找不到指定的文件。)
	at java.io.FileInputStream.open0(Native Method) ~[na:1.8.0_322]
	at java.io.FileInputStream.open(FileInputStream.java:195) ~[na:1.8.0_322]
	at java.io.FileInputStream.<init>(FileInputStream.java:138) ~[na:1.8.0_322]
	at org.apache.tomcat.util.http.fileupload.disk.DiskFileItem.getInputStream(DiskFileItem.java:198) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
	at org.apache.catalina.core.ApplicationPart.getInputStream(ApplicationPart.java:100) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
	at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile.getInputStream(StandardMultipartHttpServletRequest.java:254) ~[spring-web-5.3.22.jar:5.3.22]
	at com.tanwei.spring.app.controllers.FileController.file(FileController.java:29) ~[classes/:na]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_322]
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_322]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_322]
	at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_322]

The exception of FileNotFoundException is that the file cannot be found, that is to say, transferTo() may delete the temporary file after the transfer is completed. This is for sure, but the answer can only be said to be half right. We will analyze the source code step by step

Source code analysis

The following is based on the spring-web.5.2.9.RELEASE source code analysis of the tansferTo() method of MultipartFile
to call the tansferTo() method. Spring Boot Web calls the StandardMultipartHttpServletRequest.StandardMultipartFile.tansferTo() method by default, as shown below:

private static class StandardMultipartFile implements MultipartFile, Serializable {
    
    
		//......省略其他内容

		@Override
		public void transferTo(File dest) throws IOException, IllegalStateException {
    
    
			this.part.write(dest.getPath());
			if (dest.isAbsolute() && !dest.exists()) {
    
    
				// Servlet 3.0 Part.write is not guaranteed to support absolute file paths:
				// may translate the given path to a relative location within a temp dir
				// (e.g. on Jetty whereas Tomcat and Undertow detect absolute paths).
				// At least we offloaded the file from memory storage; it'll get deleted
				// from the temp dir eventually in any case. And for our user's purposes,
				// we can manually copy it to the requested location as a fallback.
				FileCopyUtils.copy(this.part.getInputStream(), Files.newOutputStream(dest.toPath()));
			}
		}
		
		@Override
		public void transferTo(Path dest) throws IOException, IllegalStateException {
    
    
			FileCopyUtils.copy(this.part.getInputStream(), Files.newOutputStream(dest));
		}

	}

Let's mainly look at the this.part.write(dest.getPath()); code in the .tansferTo(File dest) method. The part implementation here is ApplicationPart, as shown below:

public class ApplicationPart implements Part {
    
    
 	//......省略其他内容

    public void write(String fileName) throws IOException {
    
    
        // 构建一个需要存储的文件
        File file = new File(fileName);
        // 判断文件的地址是否是一个绝对路径地址,如C://demo/xxx.txt,返回true
        // 若文件路径不是绝对路径,将创建一个临时目录,所以这里也是经常会出现问题的地方,在使用multipartFile.tansferTo()的时候最好给绝对路径
        if (!file.isAbsolute()) {
    
    
            // 如果不是一个绝对路径地址,则在this.location下创建
            // this.location是一个临时文件对象,地址(C:\Users\xxxx\AppData\Local\Temp\tomcat.8090.3830877266980608489\work\Tomcat\localhost)
            file = new File(this.location, fileName);
        }

        try {
    
    
            this.fileItem.write(file);
        } catch (Exception var4) {
    
    
            throw new IOException(var4);
        }
    }
}

this.fileItem.write(file); This line of code is the main core code, let's continue to follow up to see what has been done, as follows:

public class DiskFileItem implements FileItem {
    
    
    //......省略其他内容

    public void write(File file) throws Exception {
    
    
        // 判断文件项是否缓存在内存中的,这里我们没设置,一般都是存在上面的临时磁盘中
        if (this.isInMemory()) {
    
    
            FileOutputStream fout = null;

            try {
    
    
                fout = new FileOutputStream(file);
                fout.write(this.get());
                fout.close();
            } finally {
    
    
                IOUtils.closeQuietly(fout);
            }
        } else {
    
    
             // 主要看一下这个代码块
            // 获取文件项的存储位置,即你上传的文件在磁盘上的临时文件
            File outputFile = this.getStoreLocation();
            if (outputFile == null) {
    
    
                throw new FileUploadException("Cannot write uploaded file to disk!");
            }
            // 获取文件长度
            this.size = outputFile.length();
            if (file.exists() && !file.delete()) {
    
    
                throw new FileUploadException("Cannot write uploaded file to disk!");
            }
            // 之所以不能再调用file.getInputStream()方法,原因就是在这
            // fileA.renameTo(fileB)方法:
            //    1) 当fileA文件信息(包含文件名、文件路径)与fileB全部相同时,只是单纯的重命名
            //    2) 当fileA文件信息(特别是文件路径)与fileB不一致时,则存在重命名和剪切,这里的剪切就会把临时文件删除,并将文件复制到fileB位置
            // 所以,在调用file.getInputStream()时,file获取的还是原始的文件位置,调用transerTo()方法后(其实调用了renameTo()),原始文件已经不存在了
            // 故而抛出FileNotFoundException异常
            if (!outputFile.renameTo(file)) {
    
    
                BufferedInputStream in = null;
                BufferedOutputStream out = null;

                try {
    
    
                    in = new BufferedInputStream(new FileInputStream(outputFile));
                    out = new BufferedOutputStream(new FileOutputStream(file));
                    IOUtils.copy(in, out);
                    out.close();
                } finally {
    
    
                    IOUtils.closeQuietly(in);
                    IOUtils.closeQuietly(out);
                }
            }
        }

    }

}

4.2 MultipartFile calls transferTo to pass in a relative path and reports FileNotFoundException

error code

@PostMapping("/uploadFile")
public String uploadImg(@RequestParam("file") MultipartFile file) {
    
    
	String baseDir = "./imgFile"; // 这里不能直接使用相对路径
	if (!file.isEmpty()) {
    
    
		String name = file.getOriginalFilename();
		String prefix = name.lastIndexOf(".") != -1 ? name.substring(name.lastIndexOf(".")) : ".jpg";
		String path = UUID.randomUUID().toString().replace("-", "") + prefix;

		try {
    
    
			// 这里代码都是没有问题的
			File filePath = new File(baseDir, path);
			// 第一次执行代码时,路径是不存在的
			logger.info("文件保存路径:{},是否存在:{}", filePath.getParentFile().exists(), filePath.getParent());
			if (!filePath.getParentFile().exists()) {
    
     // 如果存放路径的父目录不存在,就创建它。
				filePath.getParentFile().mkdirs();
			}
			// 如果路径不存在,上面的代码会创建路径,此时路径即已经创建好了
			logger.info("文件保存路径:{},是否存在:{}", filePath.getParentFile().exists(), filePath.getParent());
			// 此处使用相对路径,似乎是一个坑!
			// 相对路径:filePath
			// 绝对路径:filePath.getAbsoluteFile()
			logger.info("文件将要保存的路径:{}", filePath.getPath());

			file.transferTo(filePath);
			logger.info("文件成功保存的路径:{}", filePath.getAbsolutePath());
			return "上传成功";
		} catch (Exception e) {
    
    
			logger.error(e.getMessage());
		}
	}
	return "上传失败";
}

Once the file.transferTo(filePath) is executed, a FileNotFoundException will be generated, as shown in the figure below:

2020-11-27 10:15:06.522 ERROR 5200 --- [nio-8080-exec-1] r.controller.LearnController : java.io.FileNotFoundException: C:\Users\Alfred\AppData\Local\Temp

\tomcat.8080.2388870592947355119\work\Tomcat\localhost\ROOT\.\imgFile\684918a520684801b658c85a02bf9ba5.jpg (系统找不到指定的路径。)

The principle has been analyzed in the above question. If the void transferTo(File dest) determines that the file path is not an absolute path, a temporary directory will be created.

Solution

String baseDir = "./imgFile";
File saveFile= new File(baseDir, path);
//修改此处传如的参数,改为文件的绝对路径
multipartFile.transferTo(saveFile.getAbsoluteFile());

Five, MultipartFile and File file conversion

5.1 Convert MultipartFile to File file

5.1.1 MultipartFile.transferTo(File dest)

If the MultipartFile object is passed in at the controller layer, the MultipartFile file will be automatically cleaned up after the session ends; if the MultipartFile object is created by itself, you need to manually delete the file after use.

 @PostMapping("/upload")
    public String multipartFileTest(@ApiParam(value = "multipartFile") @RequestParam MultipartFile multipartFile,@ApiParam(value = "用户名") @RequestParam  String userName) throws Exception{
    
    
        //考虑不同浏览器上传文件会带入盘符等路径信息,此处处理一下
    	String fileName = org.apache.commons.io.FilenameUtils.getName(multipartFile.getOriginalFilename());
        File saveFile= new File("/app/home/data/",fileName );
		//修改此处传如的参数,改为文件的绝对路径
		multipartFile.transferTo(saveFile.getAbsoluteFile());
        return "成功";
    }

5.1.2 Using FileUtils.copyInputStreamToFile()

import dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.7</version>
</dependency>
  File file = new File(path,"demo.txt");
 // 得到MultipartFile文件
  MultipartFile multipartFile = getFile();
  // 把流输出到文件
  FileUtils.copyInputStreamToFile(multipartFile.getInputStream(),file);

5.2 Convert File to MultipartFile

5.2.1 使用org.springframework.mock.web.MockMultipartFile(不推荐)

(1): Using org.springframework.mock.web.MockMultipartFile needs to import spring-test.jar
该方法需要使用spring-test.jar包,生产环境一般是跳过测试包的,因此可能会导致其他问题,所以尽量不要使用这种方式

public static void main(String[] args) throws Exception {
    
    
    String filePath = "F:\\test.txt";
    File file = new File(filePath);
    FileInputStream fileInputStream = new FileInputStream(file);
    // MockMultipartFile(String name, @Nullable String originalFilename, @Nullable String contentType, InputStream contentStream)
    // 其中originalFilename,String contentType 旧名字,类型  可为空
    // ContentType.APPLICATION_OCTET_STREAM.toString() 需要使用HttpClient的包
    MultipartFile multipartFile = new MockMultipartFile("copy"+file.getName(),file.getName(),ContentType.APPLICATION_OCTET_STREAM.toString(),fileInputStream);
    System.out.println(multipartFile.getName()); // 输出copytest.txt
}

5.2.2 Using CommonsMultipartFile

import dependencies

<dependency>
	<groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;


public class Test {
    
    
   
    public static MultipartFile getMultipartFile(File file) {
    
    
        //如果传输有点问题可能传输的类型有点不同,可以试下更改为MediaType.TEXT_PLAIN_VALUE
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
    
    
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
    
    
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }
}

Guess you like

Origin blog.csdn.net/qq_43842093/article/details/131140647