upload file using jquery and handler(ashx)

后端 未结 3 935
小蘑菇
小蘑菇 2020-12-29 13:27

I am trying to upload a file using jquery ajax with handler (c#). The problem is, when I call the handler I get

context.Request.File.Count=0
3条回答
  •  梦毁少年i
    2020-12-29 13:36

    You can add this kind of code to the handler file. Then you can post to this url(whateverroot/yourhandler.ashx)

    The content type should be "multipart/form-data". For eg: If you're using a HTML form tag, then enctype="multipart/form-data".

    public void ProcessRequest(HttpContext context)
    {
            var result = "0";
            try
            {
                if (context.Request.Files.Count > 0)
                {
                    HttpPostedFile file = null;
    
                    for (int i = 0; i < context.Request.Files.Count; i++)
                    {
                        file = context.Request.Files[i];
                        if (file.ContentLength > 0)
                        {
                            var fileName = Path.GetFileName(file.FileName);
                            var path = Path.Combine(, fileName);
                            file.SaveAs(path);
                            result = "1"; 
                        }
                    }    
    
                }
            }
            catch { }
          context.Response.Write(result);
    }
    

提交回复
热议问题