1.前端页面处理
!!!我使用了form表单提交,文件下载才有反应,还不知道原因,如果有知道的大神,麻烦透露一下哦,嘻嘻
$("#download").click(function () {//按钮的点击事件
alert("aa");
var detailid = "问题";
var form = $("<form>");
form.attr("style", "display:none");
form.attr("target", "");
form.attr("method", "post");
form.attr("action", "/Home/DownloadModel");
var input9 = $("<input>");
input9.attr("type", "hidden");
input9.attr("name", "DetailID");
input9.attr("value", detailid);
$("body").append(form);
form.append(input9);
form.submit();
form.remove();
});
2.后台控制器
public ActionResult DownloadModel()
{
string detailid = Request["DetailID"];
if (detailid == "问题")
{
string fileName = "newmodel.xlsx";//客户端保存的文件名
Download(fileName);
}
return Content("ok");
}
public string Download(string fileName)
{
string path = Server.MapPath("~/modelfile/");
//工程目录中文件路径,要在自己的工程目录下创建modelfile文件夹哦
string filePath = path + fileName;
System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
if (!System.IO.File.Exists(filePath))
return "下载失败";
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
return "ok";
}