Send data as multipart/form-data

I have .NET Core back end, that receive DTO as form-data.

Here is controller

 [HttpPost]
    public async Task<IActionResult> Register([FromForm] RegisterDto model)
    {
        var result = await _authAppService.Register(model);
        if (result.Code == 409)
        {
            return BadRequest();
        }

        return Ok(result.Token);
    }

Here is DTO
 public class RegisterDto
{
    [Required]
    public string Email { get; set; }
    [Required]
    public string Password { get; set; }
    [Required]
    public string PasswordConfirmation { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    public string GcmToken { get; set; }
}

I need to send data from Angular app via form-data

I defined model at Angular side

Here is it

export class RegisterDto{
Email: string;
Password: string;
PasswordConfirmation: string;
FirstName: string;
LastName: string;

}

And this is how I try to do form-data sending

register(){
  const formData =  new FormData();
  formData.append(this.registerObject);

}

in append method I have this erroк

Expected 2-3 arguments, but got 1.ts(2554)

How I can send DTO via form data?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can’t append the whole object without giving it a field name. As the error says it acceptes 2-3 arguments however you are only providing one argument without giving it a field name.

register(){
     const formData = new FormData();
     formData.append('regObj', this.registerObject);
}

however it’s good if you append each field as formdata value such as.
formGroup: FormGroup;
formData: FormData;

register() { 
    this.formData.append('Email', this.formGroup.controls.Email.value);
    this.formData.append('Password', this.formGroup.controls.Password.value);
    this.formData.append('FirstName', this.formGroup.controls.FirstName.value);
    this.formData.append('LastName', this.formGroup.controls.LastName.value);

    // call your service and send it
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x