68

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

10 回答 10

54

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);
于 2014-09-13T06:37:25.193 回答
27
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));
于 2015-06-02T05:35:26.157 回答
20
MultipartFile multipartFile = new MockMultipartFile("test.xlsx", new FileInputStream(new File("/home/admin/test.xlsx")));

这段代码对我来说很好。可能你可以试一试。

于 2017-10-27T01:59:09.583 回答
17

就我而言,

fileItem.getOutputStream();

没有工作。因此,我使用IOUtils自己制作了它,

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);
于 2017-04-20T12:53:06.550 回答
12

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

MultipartFile fichier = new MockMultipartFile("fileThatDoesNotExists.txt",
            "fileThatDoesNotExists.txt",
            "text/plain",
            "This is a dummy file content".getBytes(StandardCharsets.UTF_8));
于 2019-04-10T16:00:09.040 回答
6
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 以便文件不会为空

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

于 2013-12-13T17:04:25.210 回答
6

没有 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);
于 2019-02-23T21:24:23.793 回答
3

如果您无法MockMultipartFile使用

import org.springframework.mock.web.MockMultipartFile;

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
于 2020-09-17T19:59:38.867 回答
1

它对我有用:

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);
于 2019-09-05T07:33:25.107 回答
1
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());
        }
    }

这对我有用。

于 2020-06-18T13:44:56.200 回答