Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

c# - 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 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[].

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...