Skip to main content

Command Palette

Search for a command to run...

How to Send data with File from Angular to Java Api.

Published
2 min read
How to Send data with File from Angular to Java Api.

Hi All

Every time there is difficulty to send both file and date at same time. We are here to see how to send both in same api.

In Angular

Create a FormData and append your file in it.

 const formData = new FormData();
    formData.append('videoFile', this.addVideoForm.value.videoFile);

Create a params attribute and set all the parameter to send with file

 let params = new HttpParams()
    .set('videoName', this.addVideoForm.value.videoName)
    .set('videoDescription', this.addVideoForm.value.videoDescription)
    .set('videoCode',this.addVideoForm.value.videoCode);

Then send both params and formData to service.

 this.service.addVideo(formData,params).subscribe((event: HttpEvent<any>) => {
      switch (event.type) {
        case HttpEventType.Sent:
          console.log('Request has been made!');
          break;
        case HttpEventType.ResponseHeader:
          console.log('Response header has been received!');
          break;
        case HttpEventType.UploadProgress:
          this.progress = Math.round(event.loaded / event.total * 100);
          console.log(`Uploaded! ${this.progress}%`);
          break;
        case HttpEventType.Response:
          console.log('User successfully created!');
          this.local_data=event.body;




          setTimeout(() => {
            this.progress = 0;
          }, 1500);

      }
    })

send both to java api like this.

addVideo(file: FormData,params:HttpParams) {



    return this.httpClient.put(this.url + '/VIDEO/', file, 
    {params: params, 
    reportProgress: true,
    observe: 'events',
    responseType: 'json' as 'json'
    });

  }

In Java

@PutMapping(value = "/")
    public ResponseEntity<Map<String, Object>> uploadVideo(
//            @ApiParam(required = true, value = "Attachment files are mandatory")
                                                               @RequestPart(value = "videoFile") MultipartFile videoFile,
//                                                           @ApiParam(required = true, value = "name is mandatory")
                                                               @RequestParam(value = "videoName",required = true) String videoName,
                                                           @RequestParam(value = "videoDescription", required = true) String videoDescription,
                                                               @RequestParam(value = "videoCode", required = true) String videocode,
                                                              ) {

Note: -Make sure attribute angular and java are must be same.

B

Nice! Great job!

D

Really awesome and helpful article. Keep ip the good work 👌

More from this blog

Samira Kumar Panigrahi's Blog

10 posts