开发场景:
文件上传接口的接收参数类型为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