Monday, May 20, 2024
Homepage · c#
 Popular · Latest · Hot · Upcoming
-1
rated 0 times [  4] [ 5]  / answers: 1 / hits: 29355  / 11 Years ago, tue, june 11, 2013, 12:00:00

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 it asynchronously, but it is not sending an upload file in the form data. No file is being sent to the server in Request.Files[].


More From » c#

 Answers
120

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.


[#77697] Sunday, June 9, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
monetm

Total Points: 615
Total Questions: 103
Total Answers: 119

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
monetm questions
Fri, Feb 26, 21, 00:00, 3 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Sun, Jul 26, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;