gpt4 book ai didi

java - 将文件转换为 MultiPartFile

转载 作者:IT老高 更新时间:2023-10-28 13:43:52 31 4
gpt4 key购买 nike

有什么方法可以将 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com