加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 将文件转换为MultiPartFile

发布时间:2020-12-14 05:29:53 所属栏目:Java 来源:网络整理
导读:有没有办法将File对象转换为MultiPartFile?所以我可以将该对象发送给接受MultiPartFile接口的对象的方法? File myFile = new File("/path/to/the/file.txt")MultiPartFile ....?def (MultiPartFile file) { def is = new BufferedInputStream(file.getInpu
有没有办法将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
}

解决方法

为此存在 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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读