当前请求不是多部分请求(角度4 +弹簧启动)

时间:2017-12-19 12:08:16

标签: angular spring-boot

我尝试使用ng-file-upload从一个角度4应用程序发送一个文件到一个弹簧启动应用程序,但抛出异常当前请求不是一个多部分请求 这是例外

  

org.springframework.web.util.NestedServletException:Request   处理失败;嵌套异常是   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)           at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)           at 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)           at 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)           at 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);

}

2 个答案:

答案 0 :(得分:2)

此代码适用于我并启动多部分请求。不需要特定的标题。

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 spring方面:

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

好的:)

答案 1 :(得分:0)

只需删除您的“内容类型”,Chrome 或 Postman 将默认设置。

你的 Rest 控制器应该:

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