1

Hay, my angular project have user register form, in that i want to upload user image and enter data push to web api. In that case i will push user entered data to json object. So i want to push upload file data and as well as other data to object body.

In separate function i will call to upload file, that's work fine.(i will do it for testing purpose, but i want to push as one object with all data)

Angular 7 cli

registed-page.component.ts

onSubmit(form:NgForm){ 
    var customerData = { 
       "cusName": form.value.userName,
       "cusPassword": form.value.password,
       "cusEmail": form.value.email, 
       "cusImage" : ############
    }; 

    //OTHER CODE TO PUSH THAT JSON OBJECT TO WEB API-------
}




 //for image upload ----------------------------------------
  public uploadFile (getData){
    if (getData.length === 0) {
      return;
    }

    let fileToUpload = <File>getData[0];
    const ImageData = new FormData();
    ImageData.append('file', fileToUpload, fileToUpload.name);

    this.http.post('https://localhost:44301/api/Customer/CustomerFileUpload', ImageData)
      .subscribe(event => {
        console.log("imae upload ----> "+event) 
      });
  }
  //for image upload ----------------------------------------

register-page-component.html

<form (ngSubmit)="onSubmit(formData)" #formData="ngForm" > 

  <input  #file type="file"  name="file" >

  <input 
  (click)="uploadFile(file.files)"   
  class="btn btn-large btn-lg btn-circle"   
  type="submit">

</form>
Thevin Malaka.
  • 151
  • 1
  • 7
  • 20

1 Answers1

1

You can convert the file to byte array/binary string/base64 and pass it with the json.

There are many ways to convert the file. Please find the post below

Convert file to byte Array

One of them is to convert it to base64:

fileToUpload.toDataURL("image/jpeg")

To pass data in formData format:

UI:

  let formData: FormData = new FormData();
  formData.append("cusImage", fileToUpload);
  formData.append('cusName', form.value.userName);
  formData.append("cusPassword", form.value.password);
  formData.append('cusEmail', form.value.email);

  this.http.post(apiUrl, formData)
  .subscribe(event => {
    console.log(event) 
  });

Backend:

Controller

    [HttpPost]
    [Route("upload")]
    public async Task<IActionResult> Upload([FromForm]FileUploadDTO model)
    {
       //Code to save data
         ...
    }

Model

public class FileUploadDTO
{
    public IFormFile cusImage { get; set; }
    public string cusName { get; set; }
    public string cusPassword { get; set; }
    public string cusEmail { get; set; }
}
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79