上传文件Spring Boot中要求的请求部分“file”不存在。

43

我想给我的Spring Boot应用程序添加上传功能;这是我的上传Rest Controller

package org.sid.web;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.sid.entities.FileInfo;

@RestController
public class UploadController {
  @Autowired
  ServletContext context;

  @RequestMapping(value = "/fileupload/file", headers = ("content-type=multipart/*"), method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  public ResponseEntity<FileInfo> upload(@RequestParam("file") MultipartFile inputFile) {
    FileInfo fileInfo = new FileInfo();
    HttpHeaders headers = new HttpHeaders();
    if (!inputFile.isEmpty()) {
      try {
        String originalFilename = inputFile.getOriginalFilename();
        File destinationFile = new File(
            context.getRealPath("C:/Users/kamel/workspace/credit_app/uploaded") + File.separator + originalFilename);
        inputFile.transferTo(destinationFile);
        fileInfo.setFileName(destinationFile.getPath());
        fileInfo.setFileSize(inputFile.getSize());
        headers.add("File Uploaded Successfully - ", originalFilename);
        return new ResponseEntity<FileInfo>(fileInfo, headers, HttpStatus.OK);
      } catch (Exception e) {
        return new ResponseEntity<FileInfo>(HttpStatus.BAD_REQUEST);
      }
    } else {
      return new ResponseEntity<FileInfo>(HttpStatus.BAD_REQUEST);
    }
  }
}

但是,当我在Postman中测试时,在插入 http://localhost:8082/fileupload/file 并将文件添加到正文时,我得到了以下错误:

"exception":org.springframework.web.multipart.support.MissingServletRequestPartException, "message":"Required request part 'file' is not present"


也许这会有所帮助 http://stackoverflow.com/questions/43864826/integration-test-case-and-file-upload/43866552#43866552 - pvpkiran
不幸的是,这并没有解决我的问题。错误仍然出现。 - Wintern
9个回答

37

以下是在Postman中您请求应该看起来的样子:

enter image description here

我的示例代码:

application.properties

#max file and request size 
spring.http.multipart.max-file-size=10MB
spring.http.multipart.max-request-size=11MB

主应用程序类:

Application.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Rest控制器类:

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


    @Controller
    @RequestMapping("/fileupload")
    public class MyRestController {

    @RequestMapping(value = "/file", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
        public @ResponseBody String myService(@RequestParam("file") MultipartFile file,
                @RequestParam("id") String id) throws Exception {

    if (!file.isEmpty()) { 

           //your logic
                        }
return "some json";

                }
    }

pom.xml

//...

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

....



<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
</dependency>

//...

6
我已将以下内容添加到我的应用程序文件中:@Bean public CommonsMultipartResolver multipartResolver() { CommonsMultipartResolver multipart = new CommonsMultipartResolver(); multipart.setMaxUploadSize(3 * 1024 * 1024); return multipart;} @Bean @Order(0) public MultipartFilter multipartFilter() { MultipartFilter multipartFilter = new MultipartFilter(); multipartFilter.setMultipartResolverBeanName("multipartReso‌​lver"); return multipartFilter; } - Wintern
1
是的,它确实做到了,因为我之前使用过Spring Boot进行开发。 - Tanmay Delhikar
谢谢,@Tanmay,我在等待。 - Wintern
1
现在它正在工作,我只是改变了函数的头部,真的非常感谢你的帮助。谢谢。 - Wintern
1
@Tanmay Delhikar,我有一个与你的样例客户端差不多的客户端,并且我正在尝试编写一个集成测试,但是一直不成功,因为我遇到了这个问题中提到的相同异常: "org.springframework.web.multipart.support.MissingServletRequestPartException","message": "Required request part 'file' is not present"。你能否简单地给出一个调用该WS的示例? - marco
显示剩余5条评论

15
在您的方法中,您已经指定了这样的方式:@RequestParam("file")。因此它期望键为file。这在异常消息中非常明显。上传文件时,请在Postman中将此名称用作Key字段。
更多信息请参见integration test case and file upload

5
谢谢您的帮助,但不幸的是那正是我所做的。 我将文件作为键传递并上传文件,但它没有起作用。 - Wintern

12

我也遇到了类似的问题,错误提示为“请求部分文件不存在”。 但后来我意识到我的应用程序中有这段代码,它导致了问题:

@Bean(name = "multipartResolver")
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver = new 
        CommonsMultipartResolver();
        multipartResolver.setMaxUploadSize(1000000000);
        return multipartResolver;
      }

我把这个移除了,现在RequestPart和RequestParam都能工作了。 请参见下面的相关问题:

https://forum.predix.io/questions/22163/multipartfile-parameter-is-not-present-error.html


我遇到了类似的问题,可能是由于我之前在Spring的早期版本上所使用的Bean;在1.5.15版本中,我不得不将其删除。 - Stefano Scarpanti
通过删除这个配置对我有用。我使用 spring-boot-2.0.2 - Eddy

8

除了其他发布的答案,问题可能与处理请求的servlet(Spring应用程序的DispatcherServlet)缺少多部分支持有关。

可以通过在web.xml声明或初始化期间(基于注释的配置的情况下)向调度程序servlet添加多部分支持来解决此问题。

a)基于web-xml的配置

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
          version="3.0">

 <servlet>
   <servlet-name>dispatcher</servlet-name>
   <servlet-class>
     org.springframework.web.servlet.DispatcherServlet
   </servlet-class>
   <init-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
   </init-param>
   <load-on-startup>1</load-on-startup>
   <multipart-config>
        <max-file-size>10485760</max-file-size>
        <max-request-size>20971520</max-request-size>
        <file-size-threshold>5242880</file-size-threshold>
    </multipart-config>
 </servlet>

</web-app>

对于基于注解的配置,应该按照以下方式进行:

public class AppInitializer implements WebApplicationInitializer { 

@Override 
public void onStartup(ServletContext servletContext) { 
    final AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext(); 

    final ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcher", new DispatcherServlet(appContext)); 
    registration.setLoadOnStartup(1); 
    registration.addMapping("/"); 

    File uploadDirectory = new File(System.getProperty("java.io.tmpdir"));                  
    MultipartConfigElement multipartConfigElement = new  MultipartConfigElement(uploadDirectory.getAbsolutePath(), 100000, 100000 * 2, 100000 / 2); 

    registration.setMultipartConfig(multipartConfigElement);
} }

接下来我们需要提供一个multipart解析器,用于解析作为multipart请求发送的文件。对于注解配置,可以按以下方式完成:

@Configuration
public class MyConfig {

@Bean
public MultipartResolver multipartResolver() {
    return new StandardServletMultipartResolver();
}
}

如果您想要使用基于xml的spring配置,您需要通过<bean>声明来将此bean添加到上下文中:

<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver" /> 

除了Spring的标准多部分解析器外,您还可以使用来自commons的实现。不过这样需要额外的依赖:

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.3</version>
</dependency>

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000000"/>
</bean>

这个答案帮助我解决了问题,非常感谢。 - Susinda Perera

0

我遇到了类似的问题,错误信息为在公共org.springframework.http.ResponseEntity中无法解析参数[0]...所需的请求部分“file”不存在,尝试了很多方法,但只有一次更改解决了这个问题。

必须进行更新。

// old
@RequestParam("file") MultipartFile inputFile


// new
@RequestParam(value = "file") MultipartFile inputFile

0
在我的情况下,我有一个多模块项目,如下所示:
核心 > API > 管理员
管理员和API是核心模块的父模块。
核心/ImageController:
@RequestMapping(value = "/upload/image", method = RequestMethod.POST)
    public ResponseEntity uploadBanner(@RequestParam(value = "file", required = 
 false) MultipartFile bannerFile){...}

AdminApplicationInitializer:

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(AdminApplicationInitializer.class);
}

@Bean
public MultipartResolver multipartResolver() {
    CommonsMultipartResolver resolver = new CommonsMultipartResolver();
    //100MB
    resolver.setMaxUploadSize(100 * (long) 1024 * 1024);
    return resolver;
}

@Bean
public MultipartConfigElement multipartConfigElement() {
    MultipartConfigFactory factory = new MultipartConfigFactory();
    factory.setMaxFileSize(DataSize.ofMegabytes(200L));
    factory.setMaxRequestSize(DataSize.ofMegabytes(200L));
    return factory.createMultipartConfig();
}

当我尝试使用核心服务“/upload/image”从api模块上传文件时,出现了错误:“所需的请求部分'file'不存在”。原因是ApiInitializer没有像AdminInitializer一样进行配置。

解决方案:我在ApiApplicationInitializer中添加了multipartResolver()multipartConfigElement()方法。然后它就可以工作了。


0
谢谢,@Eyoab,这对我有用。
我遇到了与feign客户端相同的问题。 我有一个上传文件的端点,接受Multipart文件。 主要上传端点 我使用feign客户端调用上述端点。(feign客户端方法) feign客户端调用方法 现在,你可以看到第一张图片中,该端点将文件作为@RequestParam接受。在第二张图片中,我在我的feign客户端调用中使用了@RequestPart。这帮助我解决了问题。

0
使用@RequestPart("file")而不是@RequestParam("file")

0
我也遇到了这个问题。我的代码如下:
@PostMapping("/process_contact")
    public String processContact(@ModelAttribute Contact contact, @RequestParam MultipartFile file,
            Principal p ) {
        try {
        String name=p.getName();
        User user=this.userRepository.getUserByUserName(name);
        
        //processing and uploading file
        if(file.isEmpty()) {
            System.out.println("Please Upload image");
        }
        else {
            contact.setC_imageUrl(file.getOriginalFilename());
            File saveFile=new ClassPathResource("static/image").getFile();
            Path path=Paths.get(saveFile.getAbsolutePath()+File.separator+file.getOriginalFilename());
            Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
            System.out.println("Image is uploaded");
        }
        
        
        user.getContacts().add(contact);
        contact.setUser(user);
        this.userRepository.save(user);
        System.out.println("Data" + contact);
        }catch(Exception e) {
            System.out.println("Error"+e.getMessage());
            e.printStackTrace();
        }
        return "add_contact";
    }

然后我在我的application.properties文件中添加了一个属性:
spring.servlet.multipart.enabled=true

我的错误已经解决。

你的回答目前写得不够清楚。请编辑以添加更多细节,以帮助他人理解这如何回答所提出的问题。你可以在帮助中心找到关于如何撰写好回答的更多信息。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接