angular 2 formdata empty

Ibrahim ALPSOY picture Ibrahim ALPSOY · Dec 5, 2017 · Viewed 15.3k times · Source

I can not pass data to FormData. I searched. but I could not understand. Could you please help me. My aim; image file save using web API 2. I have not written more wep api 2.

I could not find a solution. is there any other way of using it?

myComponent

let fp = new fileUploadParametre();
let formData: FormData = new FormData();
var file; 

if ($('#fileinput')[0] != undefined) {
  if ($('#fileinput')[0].files.length > 0) {
    file = $('#fileinput')[0].files[0];
    formData.append('uploadingFile', file);
    //fp.fileName = file.name;
    console.log(formData);
  }
  formData.append('siparisid', this.siparis.siparisid);
  formData.append('dokumantipi',this.form.controls.belgeTipiFormController.value);
  formData.append('aciklama',this.form.controls.aciklamaFormController.value);

  this.fileUploadService.kaydet(
    formData
  )
    .subscribe(result => {
      console.log(result);
      if (result === true) {
        this.errorMessages = [];
        this.dialogRef.close(true)
      }
      else
        this.errorMessages = ['Kayıt Yapılamadı'];
    },
    err => {
      if (err.status == 0) {
        this.errorMessages = ['Bağlantı hatası! sunucuya erişilemedi.'];
      }
      else if (err.status == 404) {
        this.errorMessages = ['Bağlantı hatası! sunucuya erişilemedi.'];
      }
      else if (err.status == 401) {
        this.errorMessages = ['Yetki Hatası.'];
      }


      else if (err.status == 400) {
        let errBody = JSON.parse(err._body);
        if (errBody
          && errBody['error'] == 'invalid_grant')
          this.errorMessages = ['Oturum Açılamadı Geçersiz Kullanıcı veya Şifre'];
        else
          this.errorMessages = [errBody.message];
      }
      else
        this.errorMessages = [err.statusTest]

    }
    );
}


 **my Service**

 public kaydet(
  formData: FormData
 ): Observable<any> {

let postFiles = {
  formData: formData
};

return this.http.post(
  this.apiUrl + '/dokumanlar/ResimKaydet',
  JSON.stringify(postFiles)
)
  .map(res => res.json());
}

formData=formData {} >> it is empty in this way.

Answer

Sina Lotfi picture Sina Lotfi · Dec 5, 2017

For sending image(avatar) to the server or web api you can use FormData and if you want to follow this purpose please do these works step by step:

  1. In html file use #avatar for accessing ElementRef in component:

    <form (ngSubmit)="onSubmit()">
        <input type="file" accept=".png, .jpg, .jpeg" #avatar>
    </form>
    

  1. Create component and using for sending image to the server;

    import {Component} from '@angular/core';
    import {ElementRef} from '@angular/core';
    import {ViewChild} from '@angular/core';
    
    import {HttpClient} from '@angular/common/http';
    import {HttpParams} from '@angular/common/http';
    import {HttpHeaders} from '@angular/common/http';
    
    @Component({
        selector: 'app-avatar',
        templateUrl: './avatar.component.html',
        styleUrls: ['./avatar.component.css']
    })
    export class AvatarComponent {
        @ViewChild('avatar') avatar: ElementRef;
    
        constructor(private http: HttpClient) { }
    
        onSubmit() {      
            const formData = new FormData();
            formData.append('avatar', 
                            this.avatar.nativeElement.files[0], 
                            this.avatar.nativeElement.files[0].name);
    
            const headers = new HttpHeaders();
            headers.append('Content-Type', 'multipart/form-data');
            headers.append('Accept', 'application/json');
            this.http.post('api/upload', formData, {headers: headers})
                .subscribe(
                    (response) => {
                    },
                    (error) => {
                    }                   
                 );
         }
    
    }
    

Notice to adding file to FormData like below method with parameters

formData.append(name, fileValue, fileName)