java将file转换为MultipartFile,完整代码
时间: 2023-08-10 22:26:32 浏览: 110
完整代码如下:
```java
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.nio.file.Files;
public class FileUtil {
public static MultipartFile fileToMultipartFile(File file) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
FileItem fileItem = new DiskFileItem("file", Files.probeContentType(file.toPath()), false, file.getName(), (int) file.length(), file.getParentFile());
try {
FileInputStream inputStream = new FileInputStream(file);
OutputStream outputStream = fileItem.getOutputStream();
IOUtils.copy(inputStream, outputStream);
inputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
return multipartFile;
}
}
```
使用时,只需要调用 fileToMultipartFile(File file) 方法即可将 File 对象转换为 MultipartFile 对象。
阅读全文