业务中需要调用别人提供的接口进行文件上传,但别人的接口只能上传MultipartFile类型的文件(吐槽一下,也不知道是哪个二货设计的这种接口)。所以需要在我们的业务代码中将File转化为MultipartFile。提供两种方法给大家。

一、使用MockMultipartFile类进行转换

这个方法比较简单,代码如下:

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 pdfFile = new File("D://test.pdf");
FileInputStream fileInputStream = new FileInputStream(pdfFile);
MultipartFile multipartFile = new MockMultipartFile(pdfFile.getName(), pdfFile.getName(),ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);

看上去很简捷,也很舒服,但需要注意,使用MockMultipartFile需要引入spring-test的依赖:版本要跟随你的spring版本定

<dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.0.8.RELEASE</version>
</dependency>

但有的项目中没有引这个jar包,而且也不允许自己引入其他jar包,并且,导入这个jar包可能会带来jar包冲突的问题。这时候就没办法了吗?并不,接下来看方法二。

二、自己实现MultipartFile接口

接口要求传MultipartFile类型,但MultipartFile是个接口,我们无法构造,也就无法传递,方法一其实就是使用了MultipartFile的一个实现类来进行传递的,很不幸,在Spring框架中,MultipartFile的实现类可不多,查看继承关系:

看上去还不少哈,其实能用的也就这个MockMultipartFile,第一个是我自己实现的,第二个是个内部类,第三个了不得,里面有FileItem这么个类,又要依赖于别的jar包,所以都不方便,只有这个MockMultipartFile,我们点进去,干干净净,就他了,为了少引一个jar包,我们就模仿MockMultipartFile自己实现MultipartFile。

有同学说,是不是实现挺麻烦呢,不,一点也不,步骤如下:

新建一个类,随便叫啥名字都可以,比如,我的类叫MultipartFileDto,去实现MultipartFile接口。然后找到MockMultipartFile类的源码,拷贝到自己这个类里面,然后,就没有然后了,完事。当然你懒直接拷贝我的代码就可以了。

MultipartFileDto的代码如下:

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;/*** @Author: szz* @Date: 2019/1/16 下午4:33* @Version 1.0** 负责将InputStream转换MultipartFile,可以少引一个jar包,本来用的是spring-test-4.3.9中的MockMultipartFile,直接提取出来使用*/
public class MultipartFileDto implements MultipartFile {private final String name;private String originalFilename;private String contentType;private final byte[] content;/*** Create a new MultipartFileDto with the given content.* @param name the name of the file* @param content the content of the file*/public MultipartFileDto(String name, byte[] content) {this(name, "", null, content);}/*** Create a new MultipartFileDto with the given content.* @param name the name of the file* @param contentStream the content of the file as stream* @throws IOException if reading from the stream failed*/public MultipartFileDto(String name, InputStream contentStream) throws IOException {this(name, "", null, FileCopyUtils.copyToByteArray(contentStream));}/*** Create a new MultipartFileDto with the given content.* @param name the name of the file* @param originalFilename the original filename (as on the client's machine)* @param contentType the content type (if known)* @param content the content of the file*/public MultipartFileDto(String name, String originalFilename, String contentType, byte[] content) {this.name = name;this.originalFilename = (originalFilename != null ? originalFilename : "");this.contentType = contentType;this.content = (content != null ? content : new byte[0]);}/*** Create a new MultipartFileDto with the given content.* @param name the name of the file* @param originalFilename the original filename (as on the client's machine)* @param contentType the content type (if known)* @param contentStream the content of the file as stream* @throws IOException if reading from the stream failed*/public MultipartFileDto(String name, String originalFilename, String contentType, InputStream contentStream)throws IOException {this(name, originalFilename, contentType, FileCopyUtils.copyToByteArray(contentStream));}@Overridepublic String getName() {return this.name;}@Overridepublic String getOriginalFilename() {return this.originalFilename;}@Overridepublic String getContentType() {return this.contentType;}@Overridepublic boolean isEmpty() {return (this.content.length == 0);}@Overridepublic long getSize() {return this.content.length;}@Overridepublic byte[] getBytes() throws IOException {return this.content;}@Overridepublic InputStream getInputStream() throws IOException {return new ByteArrayInputStream(this.content);}@Overridepublic void transferTo(File dest) throws IOException, IllegalStateException {FileCopyUtils.copy(this.content, dest);}}

他的使用方式跟MockMultipartFile一模一样,我就是直接拷贝的嘛。直接new出来就完事了。

例如:

MultipartFile multipartFile = new MultipartFileDto("temp.jpg","temp.jpg",httpEntity.getContentType().getValue(), inputStream);

三、一个非常坑的地方

我是使用的Feign的方式进行上传,feign的接口如下:

大家看红框的地方,我已经指定了上传文件的key为file,接下来进行调用,代码如下:

我使用了 public MultipartFileDto(String name, String originalFilename, String contentType, byte[] content) 这个构造方法,第一个参数name我开始写的就是realFIle的文件名,结果老是报远程服务找不到,经过我司老司机的一顿调试,发现,我们在接口的定义的@RequestPart("file") MultipartFile file中的@RequestPart("file")是无效的,这里定义的file不是请求参数的key,相当于匹配不到对应的方法,所以会报服务找不到。

而MultipartFileDto构造方法中的第一个参数name才是请求参数的key,接口中要求第一个参数是file,所以构造方法中的第一个参数写死为"file",这样再去调用就没问题了。

四、总结

接口设计者应该考虑到接口的通用性,把接收参数设计成MultipartFile看似是一种MVC的方式,其实却是非常不好的,我们来对比一下阿里云的OSS和腾讯云的COS接口设计,大家一看便知。以Java的SDK为例:

1.阿里云的文件上传SDK

https://help.aliyun.com/document_detail/61872.html?spm=5176.8465980.0.0.44781450Rethay

阿里云的上传做的极为丰富,我们只拿简单上传来对照,简单上传分为:

  • 流式上传:使用ossClient.putObject上传数据流到OSS。分文上传字符串、上传Byte数组、上传网络流、上传文件流。
// 上传字符串。
String content = "Hello OSS";
ossClient.putObject("<yourBucketName>", "<yourObjectName>", new ByteArrayInputStream(content.getBytes()));// 上传Byte数组。
byte[] content = "Hello OSS".getBytes();
ossClient.putObject("<yourBucketName>", "<yourObjectName>", new ByteArrayInputStream(content));// 上传网络流。
InputStream inputStream = new URL("https://www.aliyun.com/").openStream();
ossClient.putObject("<yourBucketName>", "<yourObjectName>", inputStream);// 上传文件流。
InputStream inputStream = new FileInputStream("<yourlocalFile>");
ossClient.putObject("<yourBucketName>", "<yourObjectName>", inputStream);
  • 文件上传
// 上传文件。<yourLocalFile>由本地文件路径加文件名包括后缀组成,例如/users/local/myfile.txt。
ossClient.putObject("<yourBucketName>", "<yourObjectName>", new File("<yourLocalFile>"));

2.腾讯云的文件上传SDK

我司用的就是腾讯云的对象存储,不得不再次吐槽一下。

https://cloud.tencent.com/document/product/436/6474

腾讯云上传做的很简陋,接下来看看API,跟上传相关的就一个PUT Object,只能传File格式。

    // 指定要上传的文件File localFile = new File("exampleobject");// 指定要上传到的存储桶String bucketName = "examplebucket-1250000000";// 指定要上传到 COS 上对象键String key = "exampleobject";PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

不解释,高下立判!


我的微信公众号:架构真经(id:gentoo666),分享Java干货,高并发编程,热门技术教程,微服务及分布式技术,架构设计,区块链技术,人工智能,大数据,Java面试题,以及前沿热门资讯等。每日更新哦!

参考资料:

  1. https://blog.csdn.net/hui008/article/details/81703342

史上最完整Java中将File转化为MultipartFile的方法(附阿里云腾讯云对象存储API对照)相关推荐

  1. 史上最全Java面试题大汇总「百题附答案」

    前言 整理这些面试题源于在微信群和几个刚入职的小伙伴们的一次讨论,很多小伙伴谈了自己的面试经历和体会,很多人最初鄙视刷题党,觉得开发技能最重要,但在短暂的面试过程中很挫败.转而去看面试题,但是网上面试 ...

  2. 2023史上最全Java面试题【完整版】跳槽必备,看完轻松收撕面试官

    ✨作者简介:杨 戬,博客专家.github开源作者 ✨多年工作总结:Java学习路线总结,小白逆袭Java技术总监 ✨技术交流:定期更新Java硬核干货,不定期送书活动.助你实现技术飞跃 ✨关注公众号 ...

  3. poi操作ppt图表史上最完整示例演示

    poi操作ppt图表史上最完整示例演示和内嵌excel的获取添加数据简单示例 ,POI3.15版本. 在模板中构造几中基本图表进行测试就行了. 完整下载地址:http://download.csdn. ...

  4. 史上最全 Java 多线程面试题及答案

    这篇文章主要是对多线程的问题进行总结的,因此罗列了40个多线程的问题. 这些多线程的问题,有些来源于各大网站.有些来源于自己的思考.可能有些问题网上有.可能有些问题对应的答案也有.也可能有些各位网友也 ...

  5. 史上最完整的文件和目录操作类

    [文件操作类]史上最完整的文件和目录操作类 <a target=_blank href="http://bbs.cskin.net/thread-114-1-1.html"& ...

  6. 史上最强Java架构师的13大技术能力讲解! | 附架构师能力图谱

    从程序员进阶成为架构师,并非一蹴而就,需要系统化.阶段性地学习,在实战项目中融会贯通,这如同打怪通关,我们得一关一关突破,每攻破一个关口,就能得到更精良的装备,技能值也随之不断增长,直至大获全胜. 凡 ...

  7. 2019史上最全java面试题题库大全800题含答案

    2019史上最全java面试题题库大全800题含答案 1. meta标签的作用是什么 2. ReenTrantLock可重入锁(和synchronized的区别)总结 3. Spring中的自动装配有 ...

  8. 2019史上最全java面试题题库大全800题含答案(面试宝典)

    2019史上最全java面试题题库大全800题含答案(面试宝典) 1. meta标签的作用是什么 2. ReenTrantLock可重入锁(和synchronized的区别)总结 3. Spring中 ...

  9. 史上最完整交互设计基本原则|推荐收藏

    史上最完整交互设计基本原则|推荐收藏 人人都是产品经理 •  2 小时前 摘要:如何设计出具有优秀用户体验的产品是交互设计师始终面临的一道难题,"好的产品设计一定是建立在对用户需求的深刻理解 ...

最新文章

  1. r语言和metawin_如何创建R的HelloWorld包(Windows或Linux环境下)
  2. 中科院计算机跨专业考研,2015考研复试:往届生和跨专业考生
  3. selenium模拟鼠标和键盘操作的基本方法
  4. Pycharm如何选择自动打开最近项目
  5. python获取视频缩略图_用 Python 代码生成视频的缩略图
  6. 中国双色向滤光镜行业市场供需与战略研究报告
  7. virtualbox+vagrant快速创建虚拟机
  8. 更开放的分布式事务 | Fescar 品牌升级,更名为 Seata
  9. 索爱确认2月13日发布Xperia Play
  10. 计算机配件详情图解,电脑装机教程,详细教您怎么组装电脑
  11. matlab sqrtm,zz矩阵开方sqrt()和sqrtm()的区别
  12. 恢复有道词典单词记录本的几种方法(非完美)
  13. Java、JSP在线问卷调查系统
  14. 心理测试软件需求分析报告,大学生心理测试软件心理测评档案管理系统
  15. 弄明白HASH,你就弄明白区块链的一大半
  16. nested exception is org.apache.ibatis.builder.BuilderException: Error evaluating expression 的解决办法
  17. Google学术无法进入的根本解决方案
  18. pycharm申请学生账号收不到邮件问题(不是你收不到而是你没找到,邮件被拦截了)
  19. 使用Server酱实现Cobalt Strike主机上线微信提醒
  20. Git和GitHub学习笔记 V2.0(更新中...)

热门文章

  1. 如何在XSLT中将字符串转换为大写或小写形式
  2. 互联网的未来之上:平权的互联网
  3. golang服务开发平滑升级之优雅重启
  4. 算法题存档20191223
  5. python38moduledocs是什么_Python模块(Module)
  6. goroutine调度详解,以及进程、线程、协程区别
  7. HashMap、ConcurretnHashMap面试题详解,源码分析
  8. 最近两天遇到的问题 原因 和处理方式 小结
  9. mysql执行代码段_mysql的event schedule 可以让你设置你的mysql数据库再某段时间执行你想要的动作...
  10. 面试官:Spring代理目标bean时为何通过TargetSource类型对目标bean封装?