起因是因为微信小程序自带的下载功能对下载文件的域名有限制,必须进行域名配置和校验之后才能下载文件,但是公司的数据是,一个客户一个域名,不可能去配置很多域名,所以就想到将文件转换成文件流的方式进行文件的预览
步骤是:
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 = new FileInfo(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; }
到此,文件已经转换成流了,小程序,通过请求这个接口,就看可以通过文件流的方式预览文件