How to set up a Web API controller for multipart/form-data

前端 未结 8 2163
萌比男神i
萌比男神i 2020-11-27 02:51

I am trying to figure this out. I was not getting any useful error messages with my code so I used something else to generate something. I have attached that code after the

8条回答
  •  鱼传尺愫
    2020-11-27 03:38

    I normally use the HttpPostedFileBase parameter only in Mvc Controllers. When dealing with ApiControllers try checking the HttpContext.Current.Request.Files property for incoming files instead:

    [HttpPost]
    public string UploadFile()
    {
        var file = HttpContext.Current.Request.Files.Count > 0 ?
            HttpContext.Current.Request.Files[0] : null;
    
        if (file != null && file.ContentLength > 0)
        {
            var fileName = Path.GetFileName(file.FileName);
    
            var path = Path.Combine(
                HttpContext.Current.Server.MapPath("~/uploads"),
                fileName
            );
    
            file.SaveAs(path);
        }
    
        return file != null ? "/uploads/" + file.FileName : null;
    }
    

提交回复
热议问题