下载文件没啥技术含量,但是我遇到个问题,执行代码后没反应,我前端是Ajax触发的。后台听说这是Ajax才会出现的问题,跟返回机制有关还好找到了解决方案
1定义一个函数
用jquery的方式组织一个字符串,模拟提交一个form请求,也就是动态渲染表单,提交表单后再删除。
jQuery.download = function (url, data, method) {
// 获取url和data
if (url && data) {
// data 是 string 或者 array/object
data = typeof data == 'string' ? data : jQuery.param(data);
// 把参数组装成 form的 input
var inputs = '';
jQuery.each(data.split('&'), function () {
var pair = this.split('=');
inputs += '<input type="hidden" name="' + pair[0] + '" value="' + pair[1] + '" />';
});
// request发送请求
jQuery('<form action="' + url + '" method="' + (method || 'post') + '">' + inputs + '</form>')
.appendTo('body').submit().remove();
};
};
2调用
$.download("/Salary/Api.aspx", "type=DownloadSalaryTemplate", 'post');
3后台
try
{
string fileName = "工资导入模板.xls";
var filePath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/Config/EmployeeSalary.xls");
FileInfo fileInfo = new FileInfo(filePath);
if (fileInfo.Exists == true)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
HttpContext.Current.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary");
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
HttpContext.Current.Response.WriteFile(fileInfo.FullName);
HttpContext.Current.Response.Flush();
}
}
catch(Exception ex)
{
}
finally
{
HttpContext.Current.Response.End();
}
return;
}
public FileResult DownloadUserTemplate()
{
string filePath = Server.MapPath("~/Content/UserImportTpl.xls");//路径
return File(filePath, "text/plain", "玩家导入模板.xls"); //welcome.txt是客户端保存的名字
}