本文章是作者在实际项目中遇到的一个问题,如何将File文件对象转MultipartFile对象。然后通过作者在自己实际操作后进行编写的该文章,本着自己记录笔记和希望能够帮助遇到同样问题的码友们!!!
话不多说,直接上源码!!!
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.*;
public class FilesUtil {
/**
* 文件对象转MultipartFile对象
* @param file 文件
* @return MultipartFile对象
*/
public static MultipartFile fileToMultipartFile(File file) {
FileItem fileItem = createFileItem(file);
return new CommonsMultipartFile(fileItem);
}
/**
* 根据File对象创建FileItem对象
* @param file File
* @return FileItem对象
*/
public static FileItem createFileItem(File file) {
FileItemFactory factory = new DiskFileItemFactory(16, null);
FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
try {
FileInputStream fis = new FileInputStream(file);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
return item;
}
}