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));
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM