将文件转换为 MultiPartFile [英] Converting File to MultiPartFile

查看:40
本文介绍了将文件转换为 MultiPartFile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 就是为了这个目的而存在的.如果文件路径已知,则在您的代码段中,以下代码适用于我.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆