ajax调用fileresult,ASP.NET MVC Controller FileContent ActionResult通过AJAX调用

这是一个快速的例子.这是LukLed正在调用SaveFile的概念,但是不要通过ajax返回文件内容,而是重定向到下载.

这是查看代码:

$(function() {

// hide form code here

// upload to server

$('#btnUpload').click(function() {

$.ajax({

type: 'POST',dataType: 'json',url: '',success: function(fileId) {

window.location = '?fileId=' + fileId;

},error: function() {

alert('An error occurred uploading data.');

}

});

});

});

Field 1:
Field 2:
Field 3:

Upload

这是控制器代码:

[HandleError]

public class HomeController : Controller

{

public ActionResult Index()

{

return View();

}

public JsonResult SaveFile(string field1,string field2,string field3)

{

// save the data to the database or where ever

int savedFileId = 1;

// return the saved file id to the browser

return Json(savedFileId);

}

public FileContentResult DownloadFile(int fileId)

{

// load file content from db or file system

string fileContents = "field1,field2,field3";

// convert to byte array

// use a different encoding if needed

var encoding = new System.Text.ASCIIEncoding();

byte[] returnContent = encoding.GetBytes(fileContents);

return File(returnContent,"application/CSV","test.csv");

}

public ActionResult About()

{

return View();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值