user14287396
user14287396

Reputation:

FormData and send image in Angular 9 and ASP.NET Core 2.1

I want to send the form information to the server, which also includes a photo, I send it correctly when sending, but the file is empty on the server side.

HTML:

<form [formGroup]="add" (ngSubmit)="submit()">
    <div class="form-group">
        <label for="file">File</label>
        <input type="file" class="form-control" (change)="onFileChange($event)">
    </div>
    <button class="btn btn-primary" type="submit">Submit</button>
</form>

Typescript:

imageSrc: string;
  add = new FormGroup({
    userName: new FormControl('Aliakbar', Validators.required),
    password: new FormControl('123', Validators.required),
    roleId: new FormControl('3', Validators.required),
    email: new FormControl('[email protected]', Validators.required),
    number: new FormControl('12344456785', Validators.required)
  });
  fileMe:File;
  onFileChange(file) {
    this.fileMe=file.target.files[0];
  }
  submit() {
    this._service.postDataUserTest(this.add.value,this.fileMe);
  }

Service:

  postDataUserTest(user: IUserTest, fileUpload: File) {
    const formData: any = new FormData();
    formData.append('file', fileUpload, fileUpload.name);
    formData.append('userName', user.userName);
    formData.append('password', user.password);
    formData.append('email', user.email);
    formData.append('number', user.number);
    formData.append('roleId', user.roleId);

    this.http.post(this.urlUser, formData).subscribe(
      (response) => console.log(response),
      (error) => console.log(error))
  }

ASP.NET Core 2.1 (Server):

public IActionResult Create([FromForm] user vUser, [FromForm] IFormFile file)
{
    .....
}

When the file is received, it is set to null.

How do I send the image?

Upvotes: 0

Views: 624

Answers (1)

Karimov
Karimov

Reputation: 359

Try to send file as FormData that's what it is for sending multiple or single file with or without fields

      fileMe:FormData;
      onFileChange(event) {
          if (event.target.files && event.target.files.length > 0) {
            const file = event.target.files[0];
            this.fileMe = new FormData();
            this.fileMe.append('file', file, file.name);
          }
        }

      submit() {
    // call your service and send it 
    this._sendfileService.sendFile(this.FinalformData)
        .subscribe( res => {
            if (res.success) { 
                console.log('file uploaded'); 
            } else { console.log('faild uploading file'))}
        })
    }
    

Service.ts file

  sendFile(file: FormData): Observable<any> {
         return this.http.post<any>(this.nodejsUrl, file);
    }

Upvotes: 1

Related Questions