Sunny Sunny - 24 days ago 14
Javascript Question

not able to upload file using Ajax.BeginForm() asynchronously

I'm trying to upload a file using Ajax.BeginForm() but it's not working out.

My View Contains:

@using (Ajax.BeginForm("UploadFile", null, new AjaxOptions { HttpMethod="POST", UpdateTargetId = "result" }, new { enctype = "multipart/form-data" }))
{
<label id="lblUploadNewFile" for="fileUploadControl">Upload New File&lt;/label>
<input type="file" name="fileToUpload" id="fileUploadControl"/>
<input id="btnFileUpload" type="submit" value="Upload" />
<span id="result" />
}


and the corresponding Controller is:

[HttpPost]
public string UploadFile(FormCollection formData)
{
HttpPostedFileBase file=null;

try
{
file = Request.Files[0];
}
catch { }

if ( file!=null &amp;&amp; file.ContentLength &gt; 0)
{
file.SaveAs(string.Concat(
AppDomain.CurrentDomain.BaseDirectory,
Path.GetFileName(file.FileName)));

return &quot;Successfully Uploaded&quot;;
}
else
{
return &quot;Upload Failed, please try again.&quot;;
}
}


The problem is that it's uploading the file but no longer doing any asynchronous posts when I remove
jquery.unobtrusive-ajax.js
. Instead, it does a full post-back.

When I add
jquery.unobtrusive-ajax.js
in my view, it's doing asynchronous but not sending upload file in form data. No file is being sent to the server in
Request.Files[]
.

Answer

You cannot upload files using AJAX. This is not supported. If you want to do that you could either use some file upload plugin such as Uploadify or Blueimp File Upload or use the HTML 5 File API if the client browser supports it.

Comments