英文:
Why the page is reloading after using a post to upload a file? (Angular + Spring Boot )
问题
文件上传功能正常,但在从后端接收响应后,应用程序正在重新加载。 <br/>
Angular 代码 <br />
HTML<br />
<input hidden="true" accept="text/pdf, .pdf" type="file" #pdfInput id="report"
(change)="validateFile($event)">
<mat-card class="reportName">
<input readonly matInput name="fileHidden" formControlName="pdfFile">
</mat-card>
<button class="mat-raised-button" [disabled]="this.uploadReport.invalid" (click)="saveReport()">上传文档</button>
TS<br />
saveReport() {
console.log(this.uploadReport.value.category);
this.reportService.saveReport(this.uploadReport.value.category, this.uploadFile).subscribe((val) => {
console.log(val);
})
}
saveReport(category :string, dataFile : FormData): Observable<ApiResponse> {
return this.http.post<ApiResponse>(this.ROOT_URL + '/report/' + category , dataFile, {reportProgress: true, responseType: 'json'});
}
Spring Boot<br/>
@PostMapping("/{category}")
public ResponseEntity<Response<String>> saveReport(@RequestParam("file") MultipartFile multipartFile,
@PathVariable String category) throws IOException
return ResponseEntity.ok(reportService.saveReport(category, multipartFile));
}
英文:
File Uploading is working but the app is reloading after receiving the response from the backend. <br/>
Angular Code <br />
HTML<br />
<input hidden="true" accept="text/pdf, .pdf" type="file" #pdfInput id="report"
(change)="validateFile($event)">
<mat-card class="reportName">
<input readonly matInput name="fileHidden" formControlName="pdfFile">
</mat-card>
<button class="mat-raised-button" [disabled]="this.uploadReport.invalid" (click)="saveReport()">Upload Document</button>
TS<br />
saveReport() {
console.log(this.uploadReport.value.category);
this.reportService.saveReport(this.uploadReport.value.category, this.uploadFile).subscribe((val) => {
console.log(val);
})
}
saveReport(category :string, dataFile : FormData): Observable<ApiResponse> {
return this.http.post<ApiResponse>(this.ROOT_URL + '/report/' + category , dataFile, {reportProgress: true, responseType: 'json'});
}
Spring boot<br />
@PostMapping("/{category}")
public ResponseEntity<Response<String>> saveReport(@RequestParam("file") MultipartFile multipartFile,
@PathVariable String category) throws IOException
return ResponseEntity.ok(reportService.saveReport(category, multipartFile));
}
答案1
得分: 0
我认为应用程序没有因为从后端接收响应而重新加载。您的上传按钮是否是表单中唯一的按钮?如果是这样,尝试阻止表单的提交行为:
<button (click)="saveReport(); $event.preventDefault()">
或者
在那个按钮上添加 type='button'。在表单中,如果一个按钮没有定义类型,它的行为类似于提交按钮。
英文:
I don't think the app is reloading due to receiving the response from the backend. Is your uploading button the only button in a form? if then try to prevent submitting behaviour of the form:
> <button (click)="saveReport(); $event.preventDefault()">
or
> Add type='button' to that button. A button without any defined type in a form acts like a submit button
专注分享java语言的经验与见解,让所有开发者获益!
评论