项目中需要调用别人的接口上传一个文件,别人的接口参数为MultipartFile类型,需要对File文件进行一个转换再进行上传
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
作为程序员第 76 篇文章,每次写一句歌词记录一下,看看人生有几首歌的时间,wahahaha …