【问题标题】:Converting File to MultiPartFile将文件转换为 MultiPartFile
【发布时间】:2013-05-20 11:30:58
【问题描述】:

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

【问题讨论】:

  • 您应该能够编写自己的实现FileItem 的类,但这需要一个实际的File 来委托,然后将此FileItem 实例传递给实现CommonsMultipartFile 的构造函数MultiPartFile
  • 我创建了一个实现 FileItem 的类,但我不知道如何实现该接口的所有方法。我在这个类中创建了一个变量File myFile。我应该只实现getinputStream()getOutputStream() 吗?
  • 特别是,我不知道您所说的“但这需要一个实际的文件来委派给”是什么意思。这是我到目前为止所拥有的:gist.github.com/birdy101/5616009
  • Something like this。未对其进行测试,但正如您所看到的可能的方法,我在artifact 上调用方法。你应该可以用new StoredFile( artifact: new File( '/path/to/file' ) ) 来构建它......手指交叉它可以工作......

标签: java spring groovy


【解决方案1】:

MockMultipartFile 就是为此目的而存在的。如果文件路径已知,则与您的 sn-p 一样,以下代码适用于我。

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

【讨论】:

  • 是否可以在不将文件保存到磁盘的情况下执行此操作?
  • @Tisha 看看我的解决方案
  • MockMultipartFile 是来自 spring 测试的类。可以将测试包含在生产中吗?
【解决方案2】:
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));

【讨论】:

    【解决方案3】:
    MultipartFile multipartFile = new MockMultipartFile("test.xlsx", new FileInputStream(new File("/home/admin/test.xlsx")));
    

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

    【讨论】:

    • user8840900 我无法导入 MockMultipartFile 。请问你能建议吗?
    • 导入org.springframework.mock.web.MockMultipartFile;
    【解决方案4】:

    就我而言,

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

    【讨论】:

    • 谢谢,这正是我所需要的!! :)
    • 最佳生产解决方案。
    • new FileInputStream(file).transferTo(fileItem.getOutputStream()); 足以防止 NPE 并复制文件内容,因此文件不会为空
    【解决方案5】:

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

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

    【讨论】:

    • 嗨,我正在尝试这个,但使用 .xlsx 扩展名和 contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"。它不适合我,请帮忙?
    • 对不起,我没有在 excel 文件上尝试过。我不知道该怎么做。也许你应该为它打开另一个线程
    【解决方案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);
    

    【讨论】:

    【解决方案7】:
    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());

    【讨论】:

    • 复制您的数据以修复 NPE:new FileInputStream(file).transferTo(fileItem.getOutputStream())
    【解决方案8】:

    如果您无法使用 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>
    

    【讨论】:

    • 谢谢!正是需要什么,没有人在任何地方解释这一点
    • 范围 = 测试?但同样,如果将范围更改为编译,我们是否不会使用测试依赖项制作产品代码?
    【解决方案9】:

    它对我有用:

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

    【讨论】:

      【解决方案10】:
      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());
              }
          }
      

      这对我有用。

      【讨论】:

      • 对于上面的代码,下面是gradle的依赖。编译组:'commons-fileupload',名称:'commons-fileupload',版本:'1.3' 编译组:'org.springframework',名称:'spring-web',版本:'3.0.4.RELEASE' 编译组:'org.springframework',名称:'spring-mock',版本:'2.0.7'
      猜你喜欢
      • 2013-05-31
      • 1970-01-01
      • 1970-01-01
      • 2020-05-07
      • 2018-12-10
      • 2013-08-10
      • 1970-01-01
      • 2020-03-02
      • 2023-03-05
      相关资源
      最近更新 更多