上传文件springboot必需的请求部分' file'不在场

时间:2017-05-12 11:09:58

标签: spring-boot upload postman spring-restcontroller

我想在我的春季启动应用程序中添加上传功能; 这是我上传的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);
    }
  }
}

但在邮递员中插入http://localhost:8082/fileupload/file并向正文添加文件时对此进行测试 我收到了这个错误:&#34; exception&#34;:&#34; org.springframework.web.multipart.support.MissingServletRequestPartException&#34;,   &#34;消息&#34;:&#34;必填请求部分&#39;文件&#39;不存在&#34;,

3 个答案:

答案 0 :(得分:12)

这是你在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);
    }
}

休息控制器类:

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>

//...

答案 1 :(得分:6)

除了其他发布的答案之外,问题可能还在于缺少处理请求的servlet的多部分支持(在Spring的应用程序中,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>

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)); dispatcher.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-request发送的文件。对于注释配置,可以通过以下方式完成:

@Configuration
public class MyConfig {

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

对于基于xml的spring配置,您需要通过标记声明声明将此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>

答案 2 :(得分:1)

我也遇到类似的问题,并且错误请求部件文件不存在。 但是后来我意识到我的应用程序中有这段代码,这会引起问题:

@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