【发布时间】:2017-01-17 13:54:52
【问题描述】:
/file/uploadfile/我正在尝试将文件上传到服务器,当用户在选择文件对话框中单击确定时。尝试实现这样的演示:http://jsfiddle.net/cHpDa/。但在控制器中我收到 NULL 而不是文件。我读过我需要对我的表单进行 ajaxify (HttpPostedFile in File Upload process is NULL if I use AJAX),但我尝试实现 ajaxify 失败了。
查看:
<script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/modernizr-2.6.2.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.form.js")" type="text/javascript"></script>
<h1>Ajax File Upload Demo</h1>
<form id="myForm" method="post" enctype="multipart/form-data">
<input type="file" size="60" name="myfile" id="myfile" />
</form>
<div id="progress">
<div id="bar"></div>
<div id="percent">0.0%</div >
</div>
<div id="message"></div>
<div id="FilesListDiv">
@Html.Partial("~/Views/File/FileList.cshtml")
</div>
<script>
$('#myfile').on("change",function(){
var options = {
type:"post",
url: "/file/uploadfile/",
beforeSend: function()
{
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function()
{
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response)
{
$("#message").html("<font color='green'>"+response.responseText+"</font>");
},
error: function()
{
$("#message").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#myForm").ajaxSubmit(options);
});
</script>
控制器:
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase myfile)
{
if (myfile != null) //here is a PROBLEM - myfile is NULL
{
this.UploadFile(myfile);
}
return PartialView("FileList");
}
【问题讨论】:
-
文件永远不能通过ajax上传
标签: jquery ajax asp.net-mvc asp.net-mvc-4