本文介绍了将文件转换为MultiPartFile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么办法将File对象转换为MultiPartFile?因此,我可以将该对象发送给接受 MultiPartFile
接口的对象的方法 File myFile = new File(/ path / to / the / file.txt)
MultiPartFile ....?
def(MultiPartFile文件){
def is = new BufferedInputStream(file.getInputStream())
//对流
做一些有趣的事情
解决方案
为此存在。正如在你的片段中,如果文件路径是已知的,下面的代码适用于我。
import java.nio.file.Files ;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.mock.web.MockMultipartFile;
Path path = Paths.get(/ path / to / the / file.txt);
String name =file.txt;
字符串originalFileName =file.txt;
String contentType =text / plain;
byte [] content = null;
尝试{
content = Files.readAllBytes(path);
} catch(final IOException e){
}
MultipartFile result = new MockMultipartFile(name,
originalFileName,contentType,content);
Is there any way to convert a File object to MultiPartFile? So that I can send that object to methods that accept the objects of MultiPartFile
interface?
File myFile = new File("/path/to/the/file.txt")
MultiPartFile ....?
def (MultiPartFile file) {
def is = new BufferedInputStream(file.getInputStream())
//do something interesting with the stream
}
解决方案
MockMultipartFile exists for this purpose. As in your snippet if the file path is known, the below code works for me.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.mock.web.MockMultipartFile;
Path path = Paths.get("/path/to/the/file.txt");
String name = "file.txt";
String originalFileName = "file.txt";
String contentType = "text/plain";
byte[] content = null;
try {
content = Files.readAllBytes(path);
} catch (final IOException e) {
}
MultipartFile result = new MockMultipartFile(name,
originalFileName, contentType, content);
这篇关于将文件转换为MultiPartFile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!