常用的请求发送会分几种:请求页面,下载文件,ajax 请求数据.
刷新页面一般用超链接发送给服务器,action 执行完,返回。
下载文件,也用超链接,到了action ,把数据写入response中,即可。
那么就是说,浏览器的返回结果,决定了是刷新页面还是下载文件(区分在于Header的标志)。
那么ajax 请求如果到一个下载文件的action, 它会下载一个文件吗?
测试结果是不行。可能浏览器有限制吧。
这个请求有xhr 标志。document 的请求是下载。
另外,下载文件有2中方式:
//public FileResult download(int id=0)
//{
// string root = Server.MapPath("~/App_Data");
// string fileName = "XMLFile1.txt";
// string filePath = Path.Combine(root, fileName);
// string s = MimeMapping.GetMimeMapping(fileName);
// return File(filePath, s, Path.GetFileName(filePath));
//}
public void download()
{
string str = "测试----下载文件的内容";
Response.Clear(); //清除缓冲区流中的所有内容输出
Response.ClearContent(); //清除缓冲区流中的所有内容输出
Response.ClearHeaders(); //清除缓冲区流中的所有头
Response.Buffer = true; //该值指示是否缓冲输出,并在完成处理整个响应之后将其发送
Response.AddHeader("Content-Disposition", "attachment;filename=123.txt");
Response.AddHeader("Content-Length", str.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.ContentType = "application/unknow"; //获取或设置输出流的 HTTP MIME 类型
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); //获取或设置输出流的 HTTP 字符集
//Response.TransmitFile(filePath);
Response.BinaryWrite(Response.ContentEncoding.GetBytes(str));
Response.End();
}