将文件转换为MultiPartFile

时间:2013-05-20 11:30:59

标签: java spring groovy

有没有办法将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
}

10 个答案:

答案 0 :(得分:27)

为此目的存在

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);

答案 1 :(得分:11)

    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));

答案 2 :(得分:8)

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

这段代码对我来说很好。也许你可以尝试一下。

答案 3 :(得分:5)

就我而言,

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);

答案 4 :(得分:3)

    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);

你需要

    fileItem.getOutputStream();

因为否则会抛出NPE。

答案 5 :(得分:0)

没有模拟类的解决方案,仅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);

答案 6 :(得分:0)

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

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

答案 7 :(得分:0)

对我有用:

文件文件= path.toFile();         字符串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);

答案 8 :(得分:0)

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());
        }
    }

这对我有用。

答案 9 :(得分:0)

如果您不能使用导入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>