使用 Spring 引导和 angular 上传文件
Upload file using Spring boot and angular
我需要使用 spring 引导和 angular 上传文件
所以这是使用 Postman
运行良好的控制器代码
@PostMapping("/uploadFile")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
String fileName = fileStorageService.storeFile(file);
String message = "";
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/downloadFile/")
.path(fileName)
.toUriString();
message = "You successfully uploaded " + file.getOriginalFilename() + "!";
return ResponseEntity.status(HttpStatus.OK).body(message);
}
但是当我以这种方式调用 angular 中的端点时
-服务代码:
pushFileToStorage(file: File): Observable<HttpEvent<{}>> {
const formdata: FormData = new FormData();
formdata.append('file', file);
const req = new HttpRequest('POST', this.indicatorUrl+'/uploadFile', formdata, {
reportProgress: true,
responseType: 'text' });
return this.httpclient.request(req);}
-Component.ts代码:
title = 'File-Upload-Save';
selectedFiles: FileList;
currentFileUpload: File;
progress: { percentage: number } = { percentage: 0 };
selectedFile = null;
changeImage = false;
change($event) {
this.changeImage = true; }
changedImage(event) {
this.selectedFile = event.target.files[0];}
upload() {
this.progress.percentage = 0;
this.currentFileUpload = this.selectedFiles.item(0);
this.indicatorservice.pushFileToStorage(this.currentFileUpload).subscribe(event => {
if (event.type === HttpEventType.UploadProgress) {
this.progress.percentage = Math.round(100 * event.loaded / event.total);
} else if (event instanceof HttpResponse) {
alert('File Successfully Uploaded');
}
this.selectedFiles = undefined;
}); }
selectFile(event) {
this.selectedFiles = event.target.files; }
-HTML代码:
<h1>Upload and Download File</h1>
<input type="file" id="customFile" (change)="selectFile($event)">
<button class="btn btn-primary" [disabled]="!selectedFiles || admincheck || status"
(click)="upload()">Save File</button>
出现这个错误
Access to XMLHttpRequest at 'http://localhost:8080/uploadFile' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
POST http://localhost:8080/uploadFile net::ERR_FAILED
ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost:8080/uploadFile", ok: false, …}
zone.js:3331 XHR failed loading: POST "http://localhost:8080/uploadFile".
我在你的代码中看到的一个主要问题,你稍后会遇到,你错过了在你的 Angular 代码中设置内容类型。
<form method="POST" enctype="multipart/form-data" action="/">
CORS 是增加安全性的网络标准。你应该详细阅读它。在您的控制器 class 添加 @CrossOrigin 注释应该可以解决问题。本教程提到了许多解决此问题的方法
https://www.baeldung.com/spring-cors
我需要使用 spring 引导和 angular 上传文件 所以这是使用 Postman
运行良好的控制器代码 @PostMapping("/uploadFile")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
String fileName = fileStorageService.storeFile(file);
String message = "";
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/downloadFile/")
.path(fileName)
.toUriString();
message = "You successfully uploaded " + file.getOriginalFilename() + "!";
return ResponseEntity.status(HttpStatus.OK).body(message);
}
但是当我以这种方式调用 angular 中的端点时
-服务代码:
pushFileToStorage(file: File): Observable<HttpEvent<{}>> {
const formdata: FormData = new FormData();
formdata.append('file', file);
const req = new HttpRequest('POST', this.indicatorUrl+'/uploadFile', formdata, {
reportProgress: true,
responseType: 'text' });
return this.httpclient.request(req);}
-Component.ts代码:
title = 'File-Upload-Save';
selectedFiles: FileList;
currentFileUpload: File;
progress: { percentage: number } = { percentage: 0 };
selectedFile = null;
changeImage = false;
change($event) {
this.changeImage = true; }
changedImage(event) {
this.selectedFile = event.target.files[0];}
upload() {
this.progress.percentage = 0;
this.currentFileUpload = this.selectedFiles.item(0);
this.indicatorservice.pushFileToStorage(this.currentFileUpload).subscribe(event => {
if (event.type === HttpEventType.UploadProgress) {
this.progress.percentage = Math.round(100 * event.loaded / event.total);
} else if (event instanceof HttpResponse) {
alert('File Successfully Uploaded');
}
this.selectedFiles = undefined;
}); }
selectFile(event) {
this.selectedFiles = event.target.files; }
-HTML代码:
<h1>Upload and Download File</h1>
<input type="file" id="customFile" (change)="selectFile($event)">
<button class="btn btn-primary" [disabled]="!selectedFiles || admincheck || status"
(click)="upload()">Save File</button>
出现这个错误
Access to XMLHttpRequest at 'http://localhost:8080/uploadFile' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
POST http://localhost:8080/uploadFile net::ERR_FAILED
ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost:8080/uploadFile", ok: false, …}
zone.js:3331 XHR failed loading: POST "http://localhost:8080/uploadFile".
我在你的代码中看到的一个主要问题,你稍后会遇到,你错过了在你的 Angular 代码中设置内容类型。
<form method="POST" enctype="multipart/form-data" action="/">
CORS 是增加安全性的网络标准。你应该详细阅读它。在您的控制器 class 添加 @CrossOrigin 注释应该可以解决问题。本教程提到了许多解决此问题的方法 https://www.baeldung.com/spring-cors