文件上传不工作

问题描述:

我已经提交了MVC3文件normally.Now我需要做Ajax.So我用这个jQuery插件一样:http://jquery.malsup.com/form/#ajaxSubmit文件上传不工作

查看代码:

$(document).ready(function() { 
     var options = { 
      url: "/Home/TakeFile", 
      dataType: "json", 
      success: showResponse 
     }; 


     $("#File").submit(function() { 
      alert("submit"); 
      $(this).ajaxSubmit(options); 
      return false; 
     }); 
    }); 


    function showResponse(responseText, statusText, xhr, $form) { 
     alert("showResponse"); 
     alert(responseText.fileName); 
    } 
</script> 

@using (Html.BeginForm("TakeFile", "Home", FormMethod.Post, new { @id = "File", enctype = "multipart/form-data" })) 
{ 
    <input type="file" id="file" /> 
    <input type="submit" value="Click to submit" id="button" /> 
} 

控制器代码:

[HttpPost] 
     public ActionResult TakeFile(HttpPostedFileBase file) 
     { 
      return Json(new { fileName=file.FileName}); 
     } 

在我的 'TakeFile' 方法的文件参数总是null.Can't似乎得到它working.Also,它使用“的Ajax我们可以做.BeginForm()'helper?

+0

文件只是不上传...否则它会在控制器适当的方法,还我可以给它被正确接收的“showResponse方法()” – 2012-04-16 14:07:26

名称一个<form>内的<input> html元素的属性使用的形式被提交之后,以引用的表单数据。

注意:只有具有name属性的表单元素在提交表单时才会传递其值。

由于动作方法public ActionResult TakeFile(HttpPostedFileBase file){..}有一个参数名称'文件',在该视图中,文件输入元素应该具有name='file'属性。更新代码:

@using (Html.BeginForm("TakeFile", "Home", FormMethod.Post, new { @id = "File", enctype = "multipart/form-data" })) 
{ 
    <input type="file" id="file" name="file" /> 
    <input type="submit" value="Click to submit" id="button" /> 
} 
+0

谢谢..这是唯一的缺陷..错过了输入类型的名称属性! – 2012-04-17 06:36:46

尝试使用如下

<input type="file" id="file" name = "attachment"/> 

控制器内添加以下代码获取文件对象

var file = Request.Files["attachment"]; 
+0

都能跟得上回一个响应。 ..var文件为空。 – 2012-04-16 12:39:06

+0

这是因为您也在发送Ajax请求。停止Ajax请求并再试一次,这应该是可行的,因为我在 – Jayanga 2012-04-17 02:49:24

dataType:json在您选择上传文件时似乎很奇怪,你有没有尝试删除它?

也可以尝试使用Name属性与输入型

<input type="file" id="file" name="file" /> 
+0

之前使用过这段代码。实际上,'datatype'告诉你从服务器获得的响应类型,而不是请求的响应类型。 – 2012-04-16 15:17:03

+0

是的,这是真的。我只是看到表单的id与输入类型的id相同.. – 2012-04-16 15:22:04

+0

Oh..yeah ...将更改任何一个id并查看 – 2012-04-16 15:25:58

据我所知,你不能通过AJAX上传文件...需要一个完整的回传后的文件。

你需要一个闪存解决方案或类似的东西,以使其发生。 使用UPLOADIFY例如...

See this blog post to make it work

+0

Yup。即使我使用的是一个插件,不同的插件虽然 – 2012-04-17 06:39:29

+0

你在用什么?我没有找到适合我的案例的最佳解决方案。 – Romias 2012-04-17 16:54:32

+1

这个插件运行良好:http://jquery.malsup.com/form/#ajaxSubmit 仍然必须在我的实际项目中使用它,并看到虽然。此代码是一个示例。 – 2012-04-18 07:36:46