Pass Httppostfilebase as parameter in the API method

Asked

Viewed 56 times

0

I have an Api that makes employee registration and also a photo, in the parameter I pass the object and a type htttppostfilebase, but when sending to api in my debug is not even hitting the method, removing from the parameter works.

My API:

        [ResponseType(typeof(Employee))]
    [HttpPost]
    public IHttpActionResult AddEmployee(Employee employee,HttpPostedFileBase file)
    {
        if (employee != null)
        {
            SqlEmployee.CreateEmployee(employee);

            string path = string.Empty;
            string pic = string.Empty;

            if (file != null)
            {
                pic = Path.GetFileName(employee.Picture);
                path = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/Employee/"), pic);
                file.SaveAs(path);
                using (MemoryStream ms = new MemoryStream())
                {
                    file.InputStream.CopyTo(ms);
                    byte[] array = ms.GetBuffer();
                }
           }

        }

        return Ok(employee);

    }

My controller:

        [HttpPost]
   public ActionResult AddOrEdit(EmployeeViewModel employee, HttpPostedFileBase file)
    {

        if (employee.Id == 0)
        {
            ViewBag.OcupationId = new SelectList(db.Occupation.ToList(), "Id", "Name");



            byte[] Bytes = new byte[file.InputStream.Length + 1];
             file.InputStream.Read(Bytes, 0, Bytes.Length);
             var fileContent = new ByteArrayContent(Bytes);
             fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = file.FileName };
             string filename = fileContent.Headers.ContentDisposition.FileName;
             employee.Picture = string.Format("~/Content/Employee/{0}", filename);


            HttpResponseMessage response = GlobalVariables.WebApiClient.PostAsJsonAsync("Employee/AddEmployee?file="+file,employee).Result;
             TempData["SuccessMessage"] = "Empregado cadastrado com sucesso!";


        }

        return RedirectToAction("Index");
    }

1 answer

1


You can access the files posted with Request.Files, in this way:

 if( Request.Files.Count > 0 ) // Se tiver algum arquivo na stream de requisição
 {
      var file = Request.Files[ 0 ]; //Pega ele.    
      //Código, código código...
 }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.