简体   繁体   English

Spring Boot + Angular文件上传无法两次上传同一文件

[英]Spring Boot + Angular file upload unable to upload same file twice

Error under Network in chrome Chrome中的网络下错误

{ timeStamp: ......, status: 400
  error: 'Bad Request',
  message: 'Required request part 'file' is not present'
  path: 'url as hosted on Tomcat'
}

Spring Boot Controller.java file Spring Boot Controller.java文件

@PostMapping("/Post")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") 
MultipartFile file){ String Message=""; try .......(and so on)}

My Angular Component 我的角度组件

<form [formGroup]="uploadForm" (ngSubmit) = "onSubmit()">
<input type="file" id="selectFile" formControlName="file1" name="selectFile"
(change)="fileEvent($event)"/>

<input type="submit" name="Submit"/>
</form>

Component.ts file Component.ts文件

fileEvent(e) {
 this.data = e.target.files[0];
}
omSubmit() {
  let headers: any = new Headers();
  headers.append('Content-type', 'undefined');
  let formData = new FormData();
  formData.append("selectFile", this.data);
  const req5 = new HttpRequest('POST', 'url as hosted on TOMCAT', formData,
  reportProgress: true,
  responseType: 'text'
  });
  return this.httpClient.request(req5).subscribe(e => {(
  console.log(e);
  )}
}

Where am I making a mistake? 我在哪里出错?

This: 这个:

formData.append("selectFile", this.data);

to that: 对此:

formData.append("file", this.data);

Cause 原因

public ResponseEntity<String> handleFileUpload(@RequestParam("file") 

Param annotation in your controller looks for a field called file . 控制器中的参数注释会查找一个名为file的字段。

Change selectFile to file will solve the problem. selectFile更改为file将解决问题。

formData.append("file", this.data);

Parameter name matters in this, it has to be same in both Java & Angular 参数名称很重要,在JavaAngular必须相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM