File类型转换为MultipartFile 类型

本文详细介绍了如何在Java中将File类型转换为MultipartFile类型,适用于在开发场景中需要将本地文件上传到服务器的情况。文章提供了具体的代码示例,并解释了在使用MockMultipartFile时的注意事项,以及正式发布时推荐使用的CommonsMultipartFile类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

开发场景:

文件上传接口的接收参数类型为MultipartFile,而我需要对数据库进行铺基础数据,就需要遍历本地文件夹,这样获取的是File类型的文件,所以需要对File进行类型转换,直接强转类型运行时会报错。需要使用流进行转换。

类型转换代码:

//需要导的jar包
import java.io.File;
import java.io.FileInputStream;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.mock.web.MockMultipartFile;
import org.apache.http.entity.ContentType; 
 

//File类型转换MultipartFile代码
File file = new File("D://temp/ren.pdf");
FileInputStream fileInputStream = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),					
                         ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
<!-- https://mvnrepository.com/artifact/org.wso2.apache.httpcomponents/httpmime --><dependency>
	<groupId>org.wso2.apache.httpcomponents</groupId>
	<artifactId>httpmime</artifactId>
	<version>4.3.1.wso2v1</version>
</dependency>

================ 补充 MockMultipartFile 的 maven 依赖 ====================

<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-test</artifactId>
	<version>5.1.9.RELEASE</version>
    <scope>test</scope>
</dependency>

需要注意的是:MockMultipartFile是属于spring-test包下的,打包发布的时候是不会将spring-test包下的jar打包进去的,我的应用场景是发布前的数据铺垫,是在本地环境,所以是没问题的;但是正式发布的话建议用CommonsMultipartFile这个类,这个类的用法可以自行查下,不是很复杂。可以参考下这个博客:https://segmentfault.com/a/1190000015706485

 

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值