简体   繁体   中英

Spring + Angular Unable to upload same file twice

Unable to upload same file twice. If uploading different files its working

Error under Network in chrome

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

Spring Boot Controller.java file

@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

fileEvent(e) {
 this.data = e.target.files[0];
}
onSubmit() {
  let headers: any = new Headers();
  headers.append('Content-type', 'undefined');
  let formData = new FormData();
  formData.append("file", 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?

Your problem sounds like there is browser caching, whereby the first time the request goes through, and the second time something different happens. If this be the source of the problem, then you may try appending a random query parameter to the end of the POST URL, eg

var url = 'url as hosted on TOMCAT';
url = url + (new Date()).getTime();

Yes, it may seem strange to bind a query parameter to a POST request, but there should be nothing preventing you from doing this. Ideally, this would be enough to disable browser caching.

I'm quite sure that the problem is caused by the change-listener on the input field which won't fire again for the same file and you are setting the this.data to null after the first submit.

You need to reset the field by ex.: doing it "manually":

onSubmit() {
    // upload the file ...
    document.getElementById("selectFile").value = "";
}

which ist probably not the best option with Angular. Or by reseting the form:

onSubmit() {
    // upload the file ...
    this.uploadForm.reset();
}

Same answer in German

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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