1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
public partial class _404 : System.Web.UI.Page { /// <summary> /// 目标服务器URL /// </summary> private readonly string targetUrl = "目标服务器"; protected void Page_Load(object sender, EventArgs e) { var folderPath = ""; try { // PrintSeverVariables(); // 取出资源地址 var fullUrl = Request.ServerVariables["QUERY_STRING"]; // 全地址 var resourceUrl = Regex.Replace(fullUrl, @"404;https?\://[^/]+", ""); // 取出文件名 var lastMatch = Regex.Match(resourceUrl, @"[^/]+(?!.*\.xlsx?)"); if (!lastMatch.Success || lastMatch.Groups.Count < 1) { Response.StatusCode = 404; return; } var fileName = lastMatch.Groups[0].Value.Split('?')[0]; if (string.IsNullOrEmpty(fileName) || fileName.IndexOf('.') < 0) { Response.StatusCode = 404; return; } // 扩展名 var extensionName = fileName.Split('.')[1].ToLower(); if (extensionName != "xls" && extensionName != "xlsx") // 只拉取excel文件 { Response.StatusCode = 404; return; } // 拉取文件 并保存 using (var stream = Get(targetUrl + resourceUrl)) { // 创建文件夹 folderPath = Server.MapPath(resourceUrl.Replace(fileName, "").Replace("/jq", "")); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } // 保存文件 SaveFile(stream, folderPath + fileName); } // 转向拉取的静态资源 Response.ContentType = "application/octet-stream"; Response.WriteFile(folderPath + fileName); } catch (Exception ex) { Response.StatusCode = 404; return; } } /// <summary> /// 保存文件 /// </summary> /// <param name="stream"></param> /// <param name="fileName"></param> public void SaveFile(Stream stream, string fileName) { // 保存文件 using (var fs = new FileStream(fileName, FileMode.OpenOrCreate)) { stream.CopyTo(fs); fs.Close(); stream.Close(); } } /// <summary> /// Get请求 /// </summary> /// <param name="url"></param> /// <param name="postData"></param> /// <returns></returns> static Stream Get(string url) { //请求 var request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = 600000; // 600秒 request.Method = "GET"; //接收 var response = (HttpWebResponse)request.GetResponse(); return response.GetResponseStream(); } /// <summary> /// 打印环境变量 /// </summary> void PrintSeverVariables() { foreach (string key in Request.ServerVariables) { Response.Write("<b>" + key + ":</b>" + Request.ServerVariables[key] + "<br>"); } } } |