6

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.

2 Answers 2

7

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Actually, the effect of headers.append() is immutable for the headers object. Use let clonedHeaders = headers.append('Accept', 'application/json') instead.
ktretyak Thank you, If you know the best approach for coding clean please edit everything in my response
0

I passed the data via FormData in my case i used the formData.set(name, fileValue, fileName) instead of formData.append(name, fileValue, fileName) please see the LINK

  1. HTML

    <input type="file"
       name="fileItem"
       id="fileItem"  
       (change)="handleFileInput($event.target.files)"/>
    

2.Component

handleFileInput(files: FileList) {
    this.fileToUpload = files.item(0);
    this.uploadFileToServer();
  }
uploadFileToServer() {
this.fileUploadService.UploadFile(this.fileToUpload).subscribe(data => {
}, error => {
  console.log(error);
});}

3.Service

UploadFile(fileToUpload: File): Observable<boolean> {
const endpoint = 'api/image/upload';
var formData = new FormData();
formData.set('file', fileToUpload);
return this._http
  .post(endpoint, formData)
  .map(() => { return true; })
  .catch((e) => this.handleError(e));}

4. Server

[Route("upload")]

public IHttpActionResult UploadImage()
{
    try
    {

        var httpRequest = HttpContext.Current.Request;

        foreach (string file in httpRequest.Files)
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);

            var postedFile = httpRequest.Files[file];
            if (postedFile != null && postedFile.ContentLength > 0)
            {

                int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB  
                IList<string> AllowedFileExtensions = new List<string> { ".jpg", ".gif", ".png" };
                var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
                var extension = ext.ToLower();
                if (!AllowedFileExtensions.Contains(extension))
                {

                    var message = string.Format("Please Upload image of type .jpg,.gif,.png.");

                    dict.Add("error", message);
                    return Ok();
                }
                else if (postedFile.ContentLength > MaxContentLength)
                {
                    var message = string.Format("Please Upload a file upto 1 mb.");
                    dict.Add("error", message);
                    return Ok();
                }
                else
                {
                   var filePath = HttpContext.Current.Server.MapPath("~/Userimage/" + postedFile.FileName + extension);
                    postedFile.SaveAs(filePath);
                }
            }
            var message1 = string.Format("Image Updated Successfully.");
            return Ok();
        }
        var res = string.Format("Please Upload a image.");
        dict.Add("error", res);
        return Ok();
    }
    catch (Exception ex)
    {
        var res = string.Format("some Message");
        dict.Add("error", res);
        return Ok();

    }}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.