[HttpGet,Route("FileDownSave")] public async Task<CustomResponse<ResultCode>> FileDownSave() { CustomResponse < ResultCode > res = new(); var edi_FileList= _fileFmsService.GetEdiFileList();//获取oss文件信息 try { Uri uri = new Uri("https://gc.mcpsystem.com/"); httpClient.DefaultRequestHeaders.Referrer = uri; foreach (var item in edi_FileList) { if (!Directory.Exists(item.key4)) // 如果不存在就创建file文件夹 { Directory.CreateDirectory(item.key4); } if (!string.IsNullOrWhiteSpace(item.oss_url)) { string[] strArry = item.oss_url.Split('/'); item.key4 = item.key4 + "/" + strArry[strArry.Length - 1];//保存地址 } var bt = await httpClient.GetByteArrayAsync(item.oss_url); Stream responseStream = new MemoryStream(bt); Stream stream = new FileStream(item.key4, FileMode.OpenOrCreate); byte[] bArr = new byte[1024]; int size = responseStream.Read(bArr, 0, bArr.Length); while (size > 0) { stream.Write(bArr, 0, size); size = responseStream.Read(bArr, 0, bArr.Length); } stream.Close(); responseStream.Close(); } res.Msg = "操作成功"; res.Code = 200; } catch (Exception ex) { LogHelper.LogException<Exception>("下载文件出现异常,异常原因为:" + ex.Message); res.Msg = "下载文件出现异常,异常原因为:" + ex.Message; res.Code = 500; throw; } return res; } //下面的为参考 private static HttpClient httpClient = null; /// <summary> /// 下载并保存 /// </summary> /// <param name="url">网络路径</param> /// <param name="savePath">保存本地的文件夹</param> public static void FileDownSave(string url,string savePath) { if (!string.IsNullOrWhiteSpace(url)) { string[] strArry = url.Split('/'); savePath =savePath+"/"+strArry[strArry.Length - 1]; } if (httpClient == null) { httpClient = new HttpClient(); } var t = httpClient.GetByteArrayAsync(url); t.Wait(); Stream responseStream = new MemoryStream(t.Result); Stream stream = new FileStream(savePath, FileMode.Create); byte[] bArr = new byte[1024]; int size = responseStream.Read(bArr, 0, bArr.Length); while (size > 0) { stream.Write(bArr, 0, size); size = responseStream.Read(bArr, 0, bArr.Length); } stream.Close(); responseStream.Close(); }
标签:core,bArr,url,item,服务器,new,net,responseStream,size From: https://www.cnblogs.com/hmYao/p/16953124.html