angular - 当前请求不是多部分请求(Angular 4+Spring Boot)

标签 angular spring-boot

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

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Current request is not a multipart request at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) at javax.servlet.http.HttpServlet.service(HttpServlet.java:707) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at 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) at com.rs.unified.gateway.security.jwt.JWTFilter.doFilter(JWTFilter.java:50) at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61) at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131) at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61) at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at 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);

}

最佳答案

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

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

好吧:)

关于angular - 当前请求不是多部分请求(Angular 4+Spring Boot),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47886695/

相关文章:

java - javax.persistence.PersistenceContext.synchronization() 中的错误

Angular 5缓存http服务api调用

javascript - node_modules\ng2-dragula\index.js 未导出“DragulaModule”

java - 如何使用 Spring Boot Security 从 facebook 获取访问 token

java - 通过查询模式通过子对象访问父对象的 protected 字段

spring-mvc - 如何对使用 thymeleaf 的安全 Controller 进行单元测试(不获取 TemplateProcessingException)?

javascript - 对新创建的文档使用 Get() 时 Firestore 规则失败

javascript - 如何让 Angular2+ 路由器在 Angular2+/AngularJS 混合应用程序上工作?

angular - 如何使用 Angular 组件中的 DecimalPipe?

spring-boot - @RestController 方法似乎默认是事务性的,为什么?