我有一个带有angular2(2.1.0)的单页应用程序和一个带有Spring(微服务)的REST API。微服务是通过jHipster(2.3)构建的。角度服务和微服务之间的通信正常。

现在,我想从角度上传文件到春天。

我已经在我的pom.xml文件中包含了必要的库作为依赖项:

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


在春季,我将multipartfilter配置为一个bean。

见下文:

 @Configuration
 @EnableWebSecurity
 @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
 public class MicroserviceSecurityConfiguration extends WebSecurityConfigurerAdapter {

  ...

  @Override
  protected void configure(HttpSecurity http) throws Exception {
      //http.addFilterBefore(multipartFilter(), CsrfFilter.class);
      System.out.println("Loading configure");
      http
      .addFilterBefore(multipartFilter(), CsrfFilter.class)
          .csrf()
          .disable()
          .headers()
          .frameOptions()
          .disable()
      .and()
          .sessionManagement()
          .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
      .and()
          .authorizeRequests()
          .antMatchers("/api/**").authenticated()
          .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
          .antMatchers("/swagger-resources/configuration/ui").permitAll()
      .and()
          .apply(securityConfigurerAdapter());

  }

 @Bean(name = "commonsMultipartResolver")
  public CommonsMultipartResolver commonsMultipartResolver() {
      final CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
      commonsMultipartResolver.setMaxUploadSize(-1);

      return commonsMultipartResolver;
  }

 @Bean
  @Order(0)
  public MultipartFilter multipartFilter() {
          MultipartFilter multipartFilter = new MultipartFilter();
          multipartFilter.setMultipartResolverBeanName("commonsMultipartResolver");
          return multipartFilter;
  }


我的REST-API方法:

/**
 * Upload single file using Spring Controller
 */
@RequestMapping(value = "/uploadFile",
        method = RequestMethod.POST)
@Timed
public String uploadFileHandler(@RequestHeader("Authorization") String token,
        @RequestParam("uploadfile") MultipartFile file) {
    System.out.println("bin in der Methode: uploadFileHandler");
    if (!file.isEmpty()) {
        // do something
    }
}


在Angular中,我使用模块ng2-file-upload上传文件。

HTML:

<input type="file" ng2FileSelect (fileOver)="fileOverBase($event)" [uploader]="uploader" multiple  name="uploadfile"/><br/>


通过xhr-object的打字稿:

uploadFile(file: File): Promise<any> {

    return new Promise((resolve, reject) => {

        let xhr: XMLHttpRequest = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    resolve(JSON.parse(xhr.response));
                } else {
                    reject(xhr.response);
                }
            }
        };

        xhr.open('POST', this.projectAPI + '/uploadFile', true);
        // If I set the content-type
        // I don't get an answer in spring
        //xhr.setRequestHeader('Content-Type', 'multipart/form-data');
        xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('id_token'));

        let formData = new FormData();
        console.log(file.name);
        formData.append("uploadfile", file, file.name);
        xhr.send(formData);
    }).catch(this.handleError);
}


当我上传文件时,收到错误消息:

[org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'uploadfile' is not present]
... <500 Internal Server Error


怎么了?我忘记了什么吗?非常感谢您的帮助。

最佳答案

我找到了解决方案。

我在“ WebConfigurer”类中转移了配置。

@Bean(name = "commonsMultipartResolver")
public MultipartResolver multipartResolver() {
    log.info("Loading the multipart resolver");
    return new StandardServletMultipartResolver();
}


@Bean
public MultipartConfigElement multipartConfigElement() {
    MultipartConfigFactory factory = new MultipartConfigFactory();

    factory.setMaxFileSize("10MB");
    factory.setMaxRequestSize("10MB");

    return factory.createMultipartConfig();
}


在角度上,我使用了Eswar的解决方案。

现在工作正常。谢谢

07-24 19:07
查看更多