小言_互联网的博客

Java中将File转化为MultipartFile的方法

979人阅读  评论(0)

业务中需要调用别人提供的接口进行文件上传,但别人的接口只能上传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));
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public String getOriginalFilename() {
        return this.originalFilename;
    }

    @Override
    public String getContentType() {
        return this.contentType;
    }

    @Override
    public boolean isEmpty() {
        return (this.content.length == 0);
    }

    @Override
    public long getSize() {
        return this.content.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return this.content;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(this.content);
    }

    @Override
    public 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);

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

参考资料:

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

 


转载:https://blog.csdn.net/m0_37609579/article/details/100901358
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场