0

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".

1 Answer 1

1

One of the major issues which I can see in your code which you will come across, later on, You missed setting content type in your Angular code.

<form method="POST" enctype="multipart/form-data" action="/">

CORS is web standard for adding security. You should read about it in detail. Adding @CrossOrigin annotation at your controller class should fix issue. This tutorial mention many ways to fix this issue https://www.baeldung.com/spring-cors

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.