How To Accept a File POST

前端 未结 13 1705
深忆病人
深忆病人 2020-11-22 09:48

I\'m using asp.net mvc 4 webapi beta to build a rest service. I need to be able to accept POSTed images/files from client applications. Is this possible using the webapi?

13条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 10:03

    [HttpPost]
    public JsonResult PostImage(HttpPostedFileBase file)
    {
        try
        {
            if (file != null && file.ContentLength > 0 && file.ContentLength<=10485760)
            {
                var fileName = Path.GetFileName(file.FileName);                                        
    
                var path = Path.Combine(Server.MapPath("~/") + "HisloImages" + "\\", fileName);
    
                file.SaveAs(path);
                #region MyRegion
                ////save imag in Db
                //using (MemoryStream ms = new MemoryStream())
                //{
                //    file.InputStream.CopyTo(ms);
                //    byte[] array = ms.GetBuffer();
                //} 
                #endregion
                return Json(JsonResponseFactory.SuccessResponse("Status:0 ,Message: OK"), JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(JsonResponseFactory.ErrorResponse("Status:1 , Message: Upload Again and File Size Should be Less Than 10MB"), JsonRequestBehavior.AllowGet);
            }
        }
        catch (Exception ex)
        {
    
            return Json(JsonResponseFactory.ErrorResponse(ex.Message), JsonRequestBehavior.AllowGet);
    
        }
    }
    

提交回复
热议问题