简体   繁体   English

上传文件springboot所需的请求部分“文件”不存在

[英]upload file springboot Required request part 'file' is not present

I want to add an upload function to my spring boot application;我想将上传 function 添加到我的 spring 启动应用程序; this is my upload Rest Controller这是我上传的 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);
    }
  }
}

but when testing this in postman with inserting http://localhost:8082/fileupload/file and adding a file to the body i got this error: "exception": org.springframework.web.multipart.support.MissingServletRequestPartException", "message": "Required request part 'file' is not present , but when testing this in postman with inserting http://localhost:8082/fileupload/file and adding a file to the body i got this error: "exception": org.springframework.web.multipart.support.MissingServletRequestPartException", "message": "Required request part 'file' is not present

This is how your request in Postman should look like:这是您在 Postman 中的请求的样子:

在此处输入图片说明

My sample code:我的示例代码:

application.properties应用程序属性

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

Main Application Class:主要应用类别:

Application.java应用程序.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 controller class:休息控制器类:

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

//...

In your method you have specified like this在您的方法中,您已指定如下
@RequestParam("file") . @RequestParam("file") Hence it is expecting the key to be file .因此它期望密钥是file It is quite evident in the exception message.这在异常消息中非常明显。 Use this name in the Key field in Postman when you upload file.上传文件时,在 Postman 的Key字段中使用此名称。
More information here integration test case and file upload更多信息在这里集成测试用例和文件上传

I also had similar issue and was getting the error request part file not present.我也有类似的问题,并且错误请求部分文件不存在。 But I later realized that I have this code in my application which was causing problem:但后来我意识到我的应用程序中有这段代码导致了问题:

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

I removed this and it started working for both RequestPart and RequestParam.我删除了它,它开始为 RequestPart 和 RequestParam 工作。 See the related issue below:请参阅下面的相关问题:

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

Except for other posted answers, the problem might be realated to missing multipart support for the servlet handling the request (spring's DispatcherServlet in case of Spring's app).除了其他已发布的答案外,问题可能是由于缺少对处理请求的 servlet 的多部分支持(Spring 的 DispatcherServlet,如果是 Spring 的应用程序)。

This can be fixed by adding multipart support to dispatcher servlet in web.xml declaration or during initialization (in case of annotation-based config)这可以通过在 web.xml 声明中或在初始化期间(在基于注释的配置的情况下)向调度程序 servlet 添加多部分支持来解决

a) web-xml based config 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>

b) for annotation-based configuration this would be following: b) 对于基于注释的配置,这将如下:

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

Then we need to provide multipart resolver which can resolve files sent as multipart-request.然后我们需要提供多部分解析器,它可以解析作为多部分请求发送的文件。 For annotation config this can be done in following way:对于注释配置,这可以通过以下方式完成:

@Configuration
public class MyConfig {

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

For xml-based spring configuration you need to add this bean to the context via tag declaration declaration:对于基于 xml 的 spring 配置,您需要通过标签声明声明将此 bean 添加到上下文中:

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

Alternatively to spring's standard multipart resolver you can use implementation from commons.除了 spring 的标准多部分解析器,您还可以使用公共实现。 This way however extra dependency is required:但是这种方式需要额外的依赖:

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

I had similar issue with error Could not resolve parameter [0] in public org.springframework.http.ResponseEntity... Required request part 'file' is not present and tried many things but one change resolved this issue.我有类似的问题,错误Could not resolve parameter [0] in public org.springframework.http.ResponseEntity... Required request part 'file' is not present并尝试了很多事情,但一项更改解决了这个问题。

Had to update不得不更新

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 MissingServletRequestPartException:所需的请求部分“文件”不存在 Springboot - MissingServletRequestPartException: Required request part 'file' is not present Springboot Spring 文件上传 - “所需的请求部分不存在” - Spring File Upload - 'Required request part is not present' Spring Thymeleaf所需的请求部分“文件”不存在 - Spring Thymeleaf Required request part 'file' is not present Tomcat:所需的请求部分“文件”不存在 - Tomcat : Required request part 'file' is not present 出现“不存在所需的请求部分&#39;文件&#39;”错误 - Getting “Required request part 'file' is not present” error Spring Boot Required 请求部分“文件”不存在 - Spring Boot Required request part 'file' is not present AngularJS JSON Spring MVC 应用程序中的文件上传 400 Bad Request Required 请求部分不存在 - File Upload in AngularJS JSON Spring MVC application 400 Bad Request Required request part is not present 所需的请求部分“文件”不存在。 尝试上传图像,角度-&gt;春天 - Required request part 'file' is not present. Trying upload an image, angular -> spring 此请求部分“文件”不存在 - This request part 'file' is not present 所需的 MultipartFile 参数“文件”不存在 [Postman 和 Springboot] - Required MultipartFile parameter 'file' is not present [Postman and Springboot]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM