Search code examples
angularform-data

Using parameters in form data?


How can I get the data that I send with formData in the method I wrote in the web API. here I can only get the name of the image file.

My Component >>

my parameters in formdata:

1- image file

2-siparisid

3-dokumantipi

4- aciklama

@ViewChild('ufile') ufile: ElementRef;

fileUploadKaydet() {
const formData = new FormData();
let headers = new Headers();

formData.append('ufile', this.ufile.nativeElement.files[0]);
formData.append('siparisid', this.siparis.siparisid);
formData.append('dokumantipi', this.form.controls.belgeTipiFormController.value);
formData.append('aciklama', this.form.controls.aciklamaFormController.value);
let options = new RequestOptions({ headers: headers });

this.http.post('http://localhost:64478/api/dokumanlar/ResimKaydet', formData, options)
.map(res => res.json()).subscribe(  
  data => console.log('success'),  
  error => console.log(error)  
  )  
}

Web Api >>

HttpFileCollection files = HttpContext.Current.Request.Files in the line of code; I can only get the image file with. How do I get the parameters I sent with FormData? for example, how to get "siparisid"

public class SiparisDokumanController : ApiController
{
    [HttpPost]
    [AllowAnonymous]
    [Route("ResimKaydet")]
    public async Task<IHttpActionResult> ResimKaydet()
    {
        int uploadCount = 0;
        string sPath = HostingEnvironment.MapPath("");
        HttpFileCollection files = HttpContext.Current.Request.Files;

        for (int i = 0; i < files.Count; i++)
        {
            HttpPostedFile file = files[i];
            string fileName = new FileInfo(file.FileName).Name;

            if (file.ContentLength > 0)
            {

                string modifiedFileName = 
               Guid.NewGuid().ToString().Replace("-", "") + "_" + fileName;
              if (!File.Exists(sPath + Path.GetFileName(modifiedFileName)))
                {
                    file.SaveAs(sPath + Path.GetFileName(modifiedFileName));
                    uploadCount++;
          //Context.Galeri.Add(new Galeri() { Id=id, FileName = 
          "/Galeri/"+modifiedFileName, Title=fileName });
                }
            }
        }

        if (uploadCount > 0)
        {
            // db ye kaydedecek kod
            //Context.SaveChange();
            //return Ok("kayıt başarılı");
        }
        return Ok("Kayıt Başarılı");

    }
}

how can I read the last saved image file? as an example, I could not find a line of code. I need to write this code with web api 2. Thanks for your help


Solution

  • I researched. it is being taken this way.

       HttpFileCollection files = HttpContext.Current.Request.Files;
       string _siparisid = HttpContext.Current.Request["siparisid"];
       string _dokumanTipi = HttpContext.Current.Request["dokumantipi"];
       string _aciklama = HttpContext.Current.Request["aciklama"];