ajax.beginform 上传文件,jquery – Ajax.BeginForm在MVC中上传文件

我试图使用这里提到的示例

How to do a ASP.NET MVC Ajax form post with multipart/form-data?

但我不断收到“失败”的错误信息框

Index.cshtml

Files Upload

$(function() {

$("#form0").submit(function(event) {

var dataString;

event.preventDefault();

var action = $("#form0").attr("action");

if ($("#form0").attr("enctype") == "multipart/form-data") {

//this only works in some browsers.

//purpose? to submit files over ajax. because screw iframes.

//also,we need to call .get(0) on the jQuery element to turn it into a regular DOM element so that FormData can use it.

dataString = new FormData($("#form0").get(0));

contentType = false;

processData = false;

} else {

// regular form,do your own thing if you need it

}

$.ajax({

type: "POST",url: action,data: dataString,dataType: "json",//change to your own,else read my note above on enabling the JsonValueProviderFactory in MVC

contentType: contentType,processData: processData,success: function(data) {

//BTW,data is one of the worst names you can make for a variable

},error: function(jqXHR,textStatus,errorThrown) {

//do your own thing

alert("fail");

}

});

}); //end .submit()

});

@Html.Action("Files","Home")

@using (Ajax.BeginForm("Files","Home",new AjaxOptions { UpdateTargetId = "uploadDiv",HttpMethod = "Post" },new { enctype = "multipart/form-data",@id="form0"}))

{

Upload new file:

}

控制器

public PartialViewResult Files(HttpPostedFileBase file)

{

IEnumerable files;

if ((file != null) && (file.ContentLength > 0))

{

string fileName = file.FileName;

string saveLocation = @"D:\Files";

string fullFilePath = Path.Combine(saveLocation,fileName);

try

{

file.SaveAs(fullFilePath);

FileInfo fileInfo = new FileInfo(fullFilePath);

file.InputStream.Read(new byte[fileInfo.Length],file.ContentLength);

}

catch (Exception e)

{

TempData["FileUpload"] = e.Message;

return PartialView();

}

files = Directory.GetFiles(@"D:\Files\");

return PartialView(files);

}

else

{

files = Directory.GetFiles(@"D:\Files\");

return PartialView(files);

}

}

Files.cshtml

@model IEnumerable

@foreach (string f in Model)

{

@f

}

Global.asax

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值