將檔案轉換成檔案流進行輸出
阿新 • • 發佈:2021-07-15
起因是因為微信小程式自帶的下載功能對下載檔案的域名有限制,必須進行域名配置和校驗之後才能下載檔案,但是公司的資料是,一個客戶一個域名,不可能去配置很多域名,所以就想到將檔案轉換成檔案流的方式進行檔案的預覽
步驟是:
1、獲取將遠端檔案(url)下載到本地
string fileName = url.Substring(url.LastIndexOf('/') + 1); string folder = "/FileToStream/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/";//https://d4.cloudcubic.net if (!Directory.Exists(context.Server.MapPath(folder))) { Directory.CreateDirectory(context.Server.MapPath(folder)); }string avatarFileName = folder + fileName; WebClient client = new WebClient(); try { client.DownloadFile(url, context.Server.MapPath(avatarFileName)); } catch { //錯誤提示 } client.Dispose();
2、將本地檔案轉換成檔案流,並輸出
string filePath = context.Server.MapPath(avatarFileName);//路徑 try { FileInfo fileInfo = newFileInfo(filePath); context.Response.Clear(); context.Response.ClearContent(); context.Response.ClearHeaders(); context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName); context.Response.AddHeader("Content-Length", fileInfo.Length.ToString()); context.Response.AddHeader("Content-Transfer-Encoding", "binary"); context.Response.ContentType = "application/octet-stream"; context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); context.Response.WriteFile(fileInfo.FullName); context.Response.Flush(); File.Delete(context.Server.MapPath(avatarFileName)); } catch { context.Response.Write("檔案轉換成檔案流失敗"); return; }
到此,檔案已經轉換成流了,小程式,通過請求這個介面,就看可以通過檔案流的方式預覽檔案