简体   繁体   English

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

[英]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 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 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组件.ts文件

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如果这是问题的根源,那么您可以尝试将随机查询参数附加到 POST URL 的末尾,例如

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.是的,将查询参数绑定到 POST 请求似乎很奇怪,但应该没有什么可以阻止您这样做。 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.我很确定问题是由输入字段上的更改侦听器引起的,它不会再次为同一个文件触发,并且您在第一次提交后将this.data设置为 null。

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.这可能不是 Angular 的最佳选择。 Or by reseting the form:或者通过重置表单:

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

Same answer in German 相同的德语答案

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

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