常用的請求發送會分幾種:請求頁面,下載文件,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();
}