这是一个快速的例子.这是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.');
}
});
});
});
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();
}
}