java 将file转为MultipartFile
时间: 2023-11-20 18:57:44 浏览: 181
可以使用`CommonsMultipartFile`类将`File`对象转换为`MultipartFile`对象。具体步骤如下:
1.导入`commons-fileupload`和`commons-io`依赖:
```xml
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
```
2.使用`CommonsMultipartFile`类将`File`对象转换为`MultipartFile`对象:
```java
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.File;
import java.io.IOException;
public class FileUtil {
public static MultipartFile fileToMultipartFile(File file) throws IOException {
DiskFileItem fileItem = new DiskFileItem("file", FileUtils.getFile(file.getPath()).getContentType(), false, file.getName(), (int) file.length(), file.getParentFile());
fileItem.getOutputStream();
return new CommonsMultipartFile(fileItem);
}
}
```
3.调用`fileToMultipartFile`方法将`File`对象转换为`MultipartFile`对象:
```java
File file = new File("path/to/file");
MultipartFile multipartFile = FileUtil.fileToMultipartFile(file);
```
阅读全文