有什么方法可以将File对象转换为MultiPartFile?这样我就可以将该对象发送到接受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为此存在。如您的代码段中所示,如果文件路径已知,则以下代码对我有用。

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

关于java - 将文件转换为MultiPartFile,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16648549/

10-12 05:51