java中File转为MultipartFile的四种方式
问题背景
项目中需要调用别人的接口上传一个文件,别人的接口参数为MultipartFile类型,需要对File文件进行一个转换再进行上传
File转MultipartFile
1 方法一
public static MultipartFile getMultipartFile(File file) { 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); }
<span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">CommonsMultipartFile</span><span class="token punctuation">(</span>item<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
可以设置为静态方法,也可以使用对象进行调用
File file = new File("D:\\a.txt");
MultipartFile cMultiFile = getMultipartFile(file);
- 1
- 2
2 方法二
// 第二种方式
public static MultipartFile getMultipartFile(File file) {
DiskFileItem item = new DiskFileItem("file"
, MediaType.MULTIPART_FORM_DATA_VALUE
, true
, file.getName()
, (int)file.length()
, file.getParentFile());
try {
OutputStream os = item.getOutputStream();
os.write(FileUtils.readFileToByteArray(file));
} catch (IOException e) {
e.printStackTrace();
}
return new CommonsMultipartFile(item);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
可以设置为静态方法,也可以使用对象进行调用
File file = new File("D:\\a.txt");
MultipartFile cMultiFile = getMultipartFile(file);
- 1
- 2
3 方法三,创建FileItem
public static FileItem createFileItem(String filePath, String fileName){
String fieldName = "file";
FileItemFactory factory = new DiskFileItemFactory(16, null);
FileItem item = factory.createItem(fieldName, "text/plain", false,fileName);
File newfile = new File(filePath);
int bytesRead = 0;
byte[] buffer = new byte[8192];
try (FileInputStream fis = new FileInputStream(newfile);
OutputStream os = item.getOutputStream()) {
while ((bytesRead = fis.read(buffer, 0, 8192))!= -1)
{
os.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
return item;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
File file = new File("D:\\a.txt");
FileItem fileItem = createFileItem(file.getPath(),file.getName());
MultipartFile cMultiFile = new CommonsMultipartFile(fileItem);
- 1
- 2
- 3
4 方法4,添加依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
- 1
- 2
- 3
- 4
import org.springframework.mock.web.MockMultipartFile;
File file = new File(“D:\a.txt”);
MultipartFile cMultiFile = new MockMultipartFile(“file”, file.getName(), null, new FileInputStream(file));
- 1
- 2
- 3
- 4
5 如果传输有点问题可能传输的类型有点不同
MediaType.MULTIPART_FORM_DATA_VALUE
- 1
更改为
MediaType.TEXT_PLAIN_VALUE
- 1
总结
- 方法有很多,自己选一种合适的
作为程序员第 76 篇文章,每次写一句歌词记录一下,看看人生有几首歌的时间,wahahaha …