Pass HttpPostFileBase as parameter in the API method

0

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

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");
    }
    
asked by anonymous 07.04.2018 / 22:49

1 answer

1

You can access files posted with Request.Files , like this:

 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...
 }
    
09.04.2018 / 15:02