将文件转换为 MultiPartFile

新手上路,请多包涵

有什么方法可以将 File 对象转换为 MultiPartFile?这样我就可以将该对象发送到接受 MultiPartFile 接口对象的方法?

 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
}

原文由 birdy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
1 个回答

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

原文由 Arun 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题