Upload file using jquery and handler (ashx)

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

context.Request.File.Count=0 

Here is the aspx code:

 <!--aspx file code--> <script language="javascript" type="text/javascript"> $().ready(function () { $('#save').click(function (e) { CalluploaderHandler(); }); }); function CalluploaderHandler() { $.ajax({ type: "POST", url: "Services/UPloader.ashx", contentType: "application/json; charset=utf-8", success: OnComplete, error: OnFail }); return false; } function OnComplete(result) { alert('Success'); } function OnFail(result) { alert('Request failed'); } </script> </head> <body> <form enctype="multipart/form-data"> <label for="file"> Filename:</label> <input name="file" id="file" type="file"> <input id="save" name="submit" value="Submit" type="submit"> </form> </body> </html> 

C # code handler:

 /* handler*/ public void ProcessRequest(HttpContext context) { string savedFileName = ""; foreach (string file in context.Request.Files) { HttpPostedFile hpf = context.Request.Files[file] as HttpPostedFile; if (hpf.ContentLength == 0) continue; // savedFileName = context.Server.MapPath(Path.GetFileName(hpf.FileName)); // hpf.SaveAs(savedFileName); } context.Response.Write(savedFileName); } 
+7
source share
3 answers

I think the problem is with contentType try

 contentType: 'multipart/form-data', 

OR

 contentType :'application/octet-stream'; 

see this post for more information

Submitting multipart / formdata using jQuery.ajax

+3
source

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

The content type must be "multipart / form-data". For example: If you use the 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(<somepath>, fileName); file.SaveAs(path); result = "1"; } } } } catch { } context.Response.Write(result); } 
+3
source

Your code ...

 $.ajax({ type: "POST", url: "Services/UPloader.ashx", contentType: "application/json; charset=utf-8", success: OnComplete, error: OnFail }); 

.. missing data parameter. The way it is currently written doesn't send anything to the handler.

You need to pass the file to the handler using the data parameter. Please follow this link: http://www.aspdotnet-suresh.com/2015/02/jquery-upload-images-files-without-page-refresh-postaback-in-aspnet.html

+2
source

All Articles