【问题标题】:current request is not a multipart request(angular 4+spring boot)当前请求不是多部分请求(角度 4+spring boot)
【发布时间】:2018-06-01 20:55:52
【问题描述】:

我正在尝试使用 ng-file-upload 从 Angular 4 应用程序向 Spring Boot 应用程序发送文件,但抛出异常当前请求不是多部分请求 这是例外

org.springframework.web.util.NestedServletException: 请求 处理失败;嵌套异常是 org.springframework.web.multipart.MultipartException:当前请求 不是多部分请求 在 org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982) 在 org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) 在 javax.servlet.http.HttpServlet.service(HttpServlet.java:707) 在 org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) 在 javax.servlet.http.HttpServlet.service(HttpServlet.java:790) 在 io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85) 在 io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129) 在 com.rs.unified.gateway.security.jwt.JWTFilter.doFilter(JWTFilter.java:50) 在 io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61) 在 io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131) 在 org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96) 在 org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 在 io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61) 在 io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131) 在 org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) 在 org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) 在 org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) 在 org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 在 org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) 在 org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 在 org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) 在 org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 在 org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)

upload(item: FileItem ) {
const copy: File =  item._file;
const fd = new FormData();
fd.append('file', copy);
   this.serviceData.uploadFile(fd).subscribe((res: Response) => {
    this.activeModal.close();
   },
  );
  }

/// 服务代码

uploadFile(file): Observable<any>  {
    const headers = new Headers({ 'Content-Type': 'multipart/form-data' });
    const options = new RequestOptions({ headers: headers });
    return this.http.post(this.resourceUrl, file,
     options );
  }

///java代码

@PostMapping(value = "/upload", consumes = { "multipart/form-data", MediaType.APPLICATION_JSON_VALUE })                                                                                                                 // 4.3
public ResponseEntity<Object> singleFileSend(HttpServletRequest request,@RequestPart MultipartFile file,
        RedirectAttributes redirectAttributes) {
    log.info("The received file" + file.getName());
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(null, SecurityUtils.resolveToken(request));
    RestTemplate restTemplate = new RestTemplate();
    HttpEntity<Object> entity = new HttpEntity<>(file,headers);
    ResponseEntity<Object> responseEntity = restTemplate.exchange(urlCoverage+"/coverage/uploadCoverage/", HttpMethod.POST, entity, Object.class);
    return new ResponseEntity<>(responseEntity.getBody(), null, HttpStatus.OK);

}

【问题讨论】:

  • 试试这个const headers = new Headers();
  • 我试了一下,还是不行
  • 尝试const headers = new Headers(); 和后端删除consumes = { "multipart/form-data", MediaType.APPLICATION_JSON_VALUE }
  • 同样的事情它不起作用:(!!
  • 你能发布你更新的代码吗?

标签: angular spring-boot


【解决方案1】:

此代码对我来说可以正常工作并启动多部分请求。不需要特定的标题。

html 文件:

<form (ngSubmit)="upload()" [formGroup]="form">
    <input ng-model="file_upload" name="file" type="file" (change)="fileChange($event)" #fileInput>
    <button type="submit">Submit</button>
</form> 

组件文件:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from "@angular/forms";
import { HttpClient } from '@angular/common/http';

...

form: FormGroup;
file: File;

constructor(private fb: FormBuilder, private http: HttpClient) {}

ngOnInit() {
    this.createForm();
}

// Instantiate an AbstractControl from a user specified configuration
  createForm() {
    this.form = this.fb.group({
      file_upload: null
    });
  }

  // Check for changes in files inputs via a DOMString reprsenting the name of an event
  fileChange(event: any) {
    // Instantiate an object to read the file content
    let reader = new FileReader();
    // when the load event is fired and the file not empty
    if(event.target.files && event.target.files.length > 0) {
      // Fill file variable with the file content
      this.file = event.target.files[0];
    }
  }

  // Upload the file to the API
  upload() {
    // Instantiate a FormData to store form fields and encode the file
    let body = new FormData();
    // Add file content to prepare the request
    body.append("file", this.file);
    // Launch post request
    this.http.post('http://localhost:8080/', body)
    .subscribe(
      // Admire results
      (data) => {console.log(data)},
      // Or errors :-(
      error => console.log(error),
      // tell us if it's finished
      () => { console.log("completed") }
    );
  }

Java 弹簧侧:

@PostMapping("/")
public String handleFileUpload(@RequestParam("file") MultipartFile file){
    ...
    return ..;
}

好的:)

【讨论】:

    【解决方案2】:

    只需删除您的“Content-Type”,这将由 Chrome 或 Postman 默认设置。

    你的 Rest 控制器应该:

    public ResponseEntity<Object> singleFileSend(HttpServletRequest request,@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-25
      • 2012-08-12
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 2017-06-20
      • 1970-01-01
      • 2021-11-16
      相关资源
      最近更新 更多