我正在为spring程序编写代码,并且需要将File
对象转换为MultipartFile
对象。我试图通过使用MockMultipartFile
类来做到这一点:
FileInputStream input = new FileInputStream(toUpload);
MultipartFile multipartFile = new MockMultipartFile("file",
toUpload.getName(), "text/json", IOUtils.toByteArray(input));
但是,我一直收到错误
MockMultipartFile cannot be resolved to a type
。为什么是这样?如果有帮助,我正在使用Maven,以防万一这是我不知道的依赖错误。我也尝试使用
CommonsMultipartFile
做到这一点。该代码在这里(toUpload
是我尝试转换的File
对象):DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, toUpload.getName(), (int) toUpload.length() , toUpload.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
当我尝试此方法时,出现错误
The constructor CommonsMultipartFile(DiskFileItem) is undefined
。这是为什么?编辑:这是我们的pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-uploading-files</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
最佳答案
要使用spring的MockMultipartFile
,您需要添加spring-test
作为编译依赖项(这是不寻常的,因为它通常被用作测试依赖项):
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>