无法使用 Ajax.BeginForm() 异步上传文件 [英] Not able to upload file using Ajax.BeginForm() asynchronously

查看:28
本文介绍了无法使用 Ajax.BeginForm() 异步上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Ajax.BeginForm() 上传文件,但没有成功.

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

我的观点包含:

@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" />
}

对应的Controller为:

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;;
   }
}

问题是它正在上传文件,但当我删除 jquery.unobtrusive-ajax.js 时不再做任何异步帖子.相反,它会执行完整的回发.

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.

当我在我的视图中添加 jquery.unobtrusive-ajax.js 时,它是异步执行的,但它不会在表单数据中发送上传文件.Request.Files[] 中没有文件被发送到服务器.

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

推荐答案

您无法使用 AJAX 上传文件.这不受支持.如果您想这样做,您可以使用一些文件上传插件,例如 UploadifyBlueimp 文件上传 或使用 HTML 5 File API 如果客户端浏览器支持它.

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.

这篇关于无法使用 Ajax.BeginForm() 异步上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆