1、当你知道文件地址,想获取文件流的时候:
var stream = await HttpClientFactory.Create().GetStreamAsync(fileUrl).ConfigureAwait(false);
2、如果是发送http请求,获取文件,接口返回流,那么按照下面的方式获取流:
public HttpResponseMessage MakeThePager() { try { Stream stream = ZuJuanServiceApi.CreatePaperStream(schoolPhaseId, subjectId, paperXml,extension); HttpResponseMessage message = new HttpResponseMessage(); message.Content = new StreamContent(stream); message.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); message.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = Guid.NewGuid().ToString().Replace("-", "") + "." + extension }; return message; } catch (Exception ex) { Logging.LogHelper.Logger.Error(ex.Message, ex); return new HttpResponseMessage(System.Net.HttpStatusCode.NotFound); } } public static async Task<Stream> GetAsync(string uri, object param) { string requestUri = FormatUri(uri, param); using (HttpClient httpClient = HttpClientFactory.Create()) { SetAuthentication(httpClient); httpClient.BaseAddress = new Uri(BaseUri); var result = await httpClient.GetAsync(requestUri).ConfigureAwait(false); var streamContent = result.Content as StreamContent; return await streamContent.ReadAsStreamAsync(); } }
3、获取文件流之后,接下来该下载了
public async Task<ActionResult> DownLoadAsync(string resourceJson, string albumName, string connId) { string directoryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TempFile");//存放临时文件的路径 if (!Directory.Exists(directoryPath)) Directory.CreateDirectory(directoryPath); var zipPath = Path.Combine(directoryPath, Guid.NewGuid().ToString() + ".zip"); //生成一个新的唯一的路径 Stream zipStream = await XyyZipHelper.CompressAsync(streamDict, zipPath).ConfigureAwait(false); DownLoadHelper.Update(connId, true); if (Request.UserAgent.ToUpper().Contains("FIREFOX")) { return File(zipStream, "application/x-zip-compressed", string.Concat("\"", albumName, "\".zip")); } else { return File(zipStream, "application/x-zip-compressed", string.Concat(albumName, ".zip")); } }
4、下载Excel常用方式
public ActionResult DownLoad() { var fileName = CountyModel.CountyName + "教职工" + "——" + Tools.DataType.ExcelTitle(dataType) + "表" + Currentuser.UserId + "_" + tempUserIdStr + ".xls"; string path = "/DownLoad/" + fileName; if (!Directory.Exists(Request.MapPath("/DownLoad"))) { System.IO.Directory.CreateDirectory(Request.MapPath("/DownLoad")); } using (FileStream file = new FileStream(Server.MapPath(path), FileMode.OpenOrCreate, FileAccess.ReadWrite)) { wk.Write(file);//工作簿的数据写入文件 file.Close(); //下载 FileStream fs = new FileStream(Server.MapPath(path), FileMode.Open);//重新获取文件流 byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); Response.ContentType = "application/octet-stream"; //通知浏览器下载文件而不是打开 SetExcelDownLoadHeader(path); Response.BinaryWrite(bytes); Response.Flush(); Response.End(); } //删除临时文件 if (System.IO.File.Exists(Server.MapPath(path))) { //如果存在则删除 System.IO.File.Delete(Server.MapPath(path)); } } protected void SetExcelDownLoadHeader(string path) { String agent = Request.Headers.Get("USER-AGENT"); if (agent != null && agent.IndexOf("Firefox") > -1) {// FF Response.AddHeader("Content-Disposition", "attachment; filename=" + System.IO.Path.GetFileName(Server.MapPath(path))); } else { Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(System.IO.Path.GetFileName(Server.MapPath(path)), System.Text.Encoding.UTF8)); } }