Multipartfile与File类型相互转换

转自:https://blog.csdn.net/qq_41454044/article/details/94439381


// M转F

File file = new File(path); 

FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);  

// F转M

File file = new File("src/test/resources/input.txt");

FileInputStream input = new FileInputStream(file);

// 文本文件
MultipartFile multipartFile = 
            new MockMultipartFile(file.getName(), file.getName(), "text/plain", input );


// 图片文件
MultipartFile multipartFile = new MockMultipartFile(pic.getName(),pic.getName(),"image/jpeg", input );


// 源码
/**
* Create a new MockMultipartFile 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 MockMultipartFile(
	          String name, @Nullable String originalFilename, 
                  @Nullable String contentType, InputStream contentStream)
	throws IOException {

      this(name, originalFilename, contentType, FileCopyUtils.copyToByteArray(contentStream));
}

原文地址:https://www.cnblogs.com/code-duck/p/13719313.html