Si Ci Pin
Si Ci Pin

Reputation: 21

Send Data and File image to the Back end

I have a problem to sent Data and Image from my Angular UI to the Spring Boot Backend.

My HTML:

<input type="file" (change)="onFileSelected($event)">

<button type="button" (click)="onUpload()" class="file-input">sdadsa</button>

My component:

 selectedFile:File = null;


     onFileSelected(event) {
    this.selectedFile = <File>event.target.files[0];
  }

  onUpload() {
    const fb = new FormData();
    const data = new CategoryModel("s", "s", "s", 1);

    fb.append('image', this.selectedFile, this.selectedFile.name);
    this.data.storeProduct(data, fb).subscribe(data => {
      console.log(data)
    })

  }

My service:

/** POST Product on server */
  storeProduct(category: CategoryModel, fd: FormData): Observable<any> {
    return this.http.post(this.cateogryUrl, { category, fd }).pipe(

      catchError(this.handleError<CategoryModel>('addHero'))

    )
  }

And finally my Spring Boot method:

@PostMapping
    @ResponseStatus(HttpStatus.OK)
    public void create(@RequestBody CategoryModel bike, @RequestParam("file") MultipartFile file) {


        String fileName = fileStorageService.storeFile(file);
        bike.setImagePath(fileName);
        categoryRepository.save(bike);
    }

When I send data I have this error:

org.springframework.web.multipart.MultipartException: Current request is not a multipart request

Upvotes: 2

Views: 490

Answers (1)

Zarna Borda
Zarna Borda

Reputation: 745

Add 'enctype': 'multipart/form-data' into your http request header.

var headers = new Headers();
headers.append('enctype', 'multipart/form-data' );

// HTTP POST using these headers
this.http.post(url, data, {headers: headers});

Upvotes: 1

Related Questions