java File 类型 转换成 MultipartFile

java File 类型 转换成 MultipartFile

MutipartFile是spring里面定义的接口,它封装了用户在上传图片时所包含的所有信息,但是有些时候我们要将file转换成MutipartFile,才能在保持原有代码逻辑的情况下方便代码的调整,但是file不能直接转换成MutipartFile,网上方法较多,这里采用spring-mock实现。

1.引入mock maven

<!--  File转换成MultipartFile(MutipartFile是spring里面定义的接口,它封装了用户在上传图片时所包含的所有信息,但是有些时候我们要将file转换成MutipartFile,才能在保持原有代码逻辑的情况下方便代码的调整) -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-mock</artifactId>
    <version>2.0.8</version>
</dependency>

2.使用

public static void main(String[] args) throws IOException {
    String strUrl = "C:\\Users\\84916\\Desktop\\store_data_test(1).xlsx";
    File file = new File(strUrl);
    InputStream inputStream = new FileInputStream(file);
    //mock---file转multipartfile(测试使用)
    MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(inputStream));
    List<String[]> excelData = ExcelData.getExcelData(multipartFile);
    System.out.println(excelData);
}

之前看到其他人这样使用,但是我这里实际应用需要判断文件类型,所以会报错。

 MultipartFile multipartFile = new MockMultipartFile(file.getName(), inputStream);

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值