史上最完整Java中將File轉化為MultipartFile的方法


業務中需要調用別人提供的接口進行文件上傳,但別人的接口只能上傳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>

二、自己實現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出來就完事了。

三、一個有點坑的地方

  File excelFile = new File(filePath);
  FileInputStream fileInputStream = new FileInputStream(excelFile);
  multipartFile = new MultipartFileDto(filePath, filePath, ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
  • 前兩個參數必須為filePath,否則使用easyPOI時用Deciaml校驗無法解析成功

轉載:https://blog.csdn.net/m0_37609579/article/details/100901358


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM