java中File转为MultipartFile的四种实现方式
更新时间:2024年06月15日 10:04:44 作者:时间是一种解药
这篇文章主要介绍了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);
}
return new CommonsMultipartFile(item);
}可以设置为静态方法,也可以使用对象进行调用
File file = new File("D:\\a.txt");
MultipartFile cMultiFile = getMultipartFile(file);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);
}可以设置为静态方法,也可以使用对象进行调用
File file = new File("D:\\a.txt");
MultipartFile cMultiFile = getMultipartFile(file);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;
}File file = new File("D:\\a.txt");
FileItem fileItem = createFileItem(file.getPath(),file.getName());
MultipartFile cMultiFile = new CommonsMultipartFile(fileItem);4.方法4
添加依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>import org.springframework.mock.web.MockMultipartFile;
File file = new File("D:\\a.txt");
MultipartFile cMultiFile = new MockMultipartFile("file", file.getName(), null, new FileInputStream(file));5.如果传输有点问题可能传输的类型有点不同
MediaType.MULTIPART_FORM_DATA_VALUE
更改为
MediaType.TEXT_PLAIN_VALUE
总结
方法有很多,自己选一种合适的
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
spring启动错误Singleton bean creation not al
本文主要介绍了spring启动错误Singleton bean creation not allowed while the singletons of this factory are indestruction,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2023-07-07
Java Quartz触发器CronTriggerBean配置用法详解
这篇文章主要介绍了Java Quartz触发器CronTriggerBean配置用法详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下2021-08-08
Java concurrency线程池之线程池原理(三)_动力节点Java学院整理
这篇文章主要为大家详细介绍了Java concurrency线程池之线程池原理第三篇,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-06-06


最新评论