一 使用背景:
通过Http 请求下载一个压缩的文件到服务器内存中(重点:不用保存到本地),然后通过代码直接提取压缩包的文件
二 实现思路:(注:需要提前安装 ICSharpCode.SharpZipLib.dll)
1 通过Http请求下载压缩文件到服务器的内存中
2 读取内存中压缩的包的流(注意先将:Stream 转换成MemoryStream)
3 通过ICSharpCode.SharpZipLib.Zip.dll的ZipFile方法将压缩包的MemoryStream 注入
4 通过文件索引提取压缩包里的文件流
5 保存上传文件到指定位置
三 参考代码:
1 public string HttpDownloadFile(int tenantId, RequestHeaadModel heaadModel) 2 { 3 var dfsResultPath = string.Empty; 4 var listDfsPath = new List<string>(); 5 try 6 { 7 #region Http请求参数设置 8 ServicePointManager.Expect100Continue = false; 9 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; 10 ServicePointManager.ServerCertificateValidationCallback += (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => true; 11 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(heaadModel.ResquestParamUrl); 12 request.Headers.Add("x-qys-accesstoken", heaadModel.Accesstoken); 13 request.Headers.Add("x-qys-timestamp", "0"); 14 request.Headers.Add("x-qys-signature", heaadModel.Searect); 15 request.ContentType = heaadModel.ContentType; 16 request.Method = "GET"; 17 request.Timeout = 100000; 18 request.Accept = "application/octet-stream"; 19 #endregion 20 21 #region 对响应的压缩包解析 22 using (WebResponse webRes = request.GetResponse()) 23 { 24 #region 1 获取响应的压缩包文件流 25 var length = (long)webRes.ContentLength; 26 var response = webRes as HttpWebResponse; 27 var stream = response.GetResponseStream(); 28 #endregion 29 30 #region 2 将压缩包文件流程读取到内存中 31 var stmMemory = new MemoryStream(); 32 if (length == -1) 33 { 34 length = 1024; 35 } 36 var buffer = new byte[length]; 37 int i; 38 while ((i = stream.Read(buffer, 0, buffer.Length)) > 0) 39 { 40 stmMemory.Write(buffer, 0, i); 41 } 42 #endregion 43 44 #region 3 循环读取压缩包的文件 45 var zipFile_ = new ICSharpCode.SharpZipLib.Zip.ZipFile(stmMemory); 46 int count = int.Parse(zipFile_.Count.ToString());//获取文件个数 47 for (int j = 0; j < count; j++) 48 { 49 var tempSteam = zipFile_.GetInputStream(long.Parse($"{i}"));//压缩包里的文件索引 50 var stmMemory2 = new MemoryStream(); 51 var buffer2 = new byte[zipFile_[i].Size]; 52 int m; 53 //将单个文件的文件流读取到内存中 54 while ((m = tempSteam.Read(buffer2, 0, buffer2.Length)) > 0) 55 { 56 stmMemory2.Write(buffer2, 0, m); 57 } 58 stmMemory2.Seek(0, SeekOrigin.Begin); 59 var dfsItem = new DfsItem("TenantBaseFile", zipFile_[i].Name, 60 stmMemory2, tenantId); 61 var dfsPath = Dfs.Store(dfsItem); 62 63 Logger.Debug($"下载背调文件地址:{dfsPath.ToString()}"); 64 listDfsPath.Add(dfsPath.ToString()); 65 stmMemory2.Close(); 66 stmMemory2.Flush(); 67 } 68 #endregion 69 stmMemory.Close(); 70 stmMemory.Flush(); 71 } 72 #endregion 73 } 74 catch (Exception ex) 75 { 76 Logger.Debug($"下载报告异常:异常信息:{ex.Message},堆栈信息:{ex.StackTrace}"); 77 } 78 79 return string.Join(",", listDfsPath); 80 }