i need to upload file using spring boot and angular So this is the controller code which is well worked using 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);
}
but when i called the endPoint in angular that way
-Service code:
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 code :
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 code :
<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>
This ERROR appeared
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".