将文件转换为 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
}
224279 次浏览
File file = new File("src/test/resources/validation.txt");
DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, file.getName(), (int) file.length() , file.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);

您需要以下内容来防止 NPE。

fileItem.getOutputStream();

另外,您需要将文件内容复制到 fileItem,这样 file 就不会是空的

new FileInputStream(f).transferTo(item.getOutputStream());

为此目的存在 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);
File file = new File("src/test/resources/input.txt");
FileInputStream input = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile("file",
file.getName(), "text/plain", IOUtils.toByteArray(input));

对我来说

fileItem.getOutputStream();

没有工作。因此我自己使用 白痴,

File file = new File("/path/to/file");
FileItem fileItem = new DiskFileItem("mainFile", Files.probeContentType(file.toPath()), false, file.getName(), (int) file.length(), file.getParentFile());


try {
InputStream input = new FileInputStream(file);
OutputStream os = fileItem.getOutputStream();
IOUtils.copy(input, os);
// Or faster..
// IOUtils.copy(new FileInputStream(file), fileItem.getOutputStream());
} catch (IOException ex) {
// do something.
}


MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
MultipartFile multipartFile = new MockMultipartFile("test.xlsx", new FileInputStream(new File("/home/admin/test.xlsx")));

这个代码对我来说很好用。也许你可以试一试。

解决方案没有 Mocking 类,Java9 + 和 Spring 只。

FileItem fileItem = new DiskFileItemFactory().createItem("file",
Files.probeContentType(file.toPath()), false, file.getName());


try (InputStream in = new FileInputStream(file); OutputStream out = fileItem.getOutputStream()) {
in.transferTo(out);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid file: " + e, e);
}


CommonsMultipartFile multipartFile = new CommonsMultipartFile(fileItem);

这是一个不需要手动在光盘上创建文件的解决方案:

MultipartFile fichier = new MockMultipartFile("fileThatDoesNotExists.txt",
"fileThatDoesNotExists.txt",
"text/plain",
"This is a dummy file content".getBytes(StandardCharsets.UTF_8));

这对我很有效:

File file = path.toFile();
String mimeType = Files.probeContentType(path);


DiskFileItem fileItem = new DiskFileItem("file", mimeType, false, file.getName(), (int) file.length(),
file.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


import org.apache.commons.io.IOUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;


public static void main(String[] args) {
convertFiletoMultiPart();
}


private static void convertFiletoMultiPart() {
try {
File file = new File(FILE_PATH);
if (file.exists()) {
System.out.println("File Exist => " + file.getName() + " :: " + file.getAbsolutePath());
}
FileInputStream input = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain",
IOUtils.toByteArray(input));
System.out.println("multipartFile => " + multipartFile.isEmpty() + " :: "
+ multipartFile.getOriginalFilename() + " :: " + multipartFile.getName() + " :: "
+ multipartFile.getSize() + " :: " + multipartFile.getBytes());
} catch (IOException e) {
System.out.println("Exception => " + e.getLocalizedMessage());
}
}

这招对我很管用。

如果不能使用

import org.springframework.mock.web.MockMultipartFile;

您需要将以下依赖项添加到 pom.xml:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

对于分级项目添加- 实现组: ‘ org.springframework.boot’,名称: ‘ spring-boot-starter-test’,版本: ‘2.7.4’

您可以自己创建 MultipartFile 的实现,例如:

public class JavaFileToMultipartFile implements MultipartFile {


private final File file;


public TPDecodedMultipartFile(File file) {
this.file = file;
}


@Override
public String getName() {
return file.getName();
}


@Override
public String getOriginalFilename() {
return file.getName();
}


@Override
public String getContentType() {
try {
return Files.probeContentType(file.toPath());
} catch (IOException e) {
throw new RuntimeException("Error while extracting MIME type of file", e);
}
}


@Override
public boolean isEmpty() {
return file.length() == 0;
}


@Override
public long getSize() {
return file.length();
}


@Override
public byte[] getBytes() throws IOException {
return Files.readAllBytes(file.toPath());
}


@Override
public InputStream getInputStream() throws IOException {
return new FileInputStream(file);
}


@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
throw new UnsupportedOperationException();
}
}