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