C# 下载文件
方法一:
1 2 3 4 5 6 7 8 9 10 11 | [HttpGet] [EnableCors( "userLogin" )] public IActionResult DownloadFile( string url , string token) { var filePath = "D://xzc/" + _Configuration.GetSection( "module" ).Value + "/Uploads/" + url; string [] tmpArr = url.Split( "_" ); var fileName = tmpArr.AsQueryable().Last(); ; FileStream fs = new FileStream( filePath, FileMode.OpenOrCreate); fs.Close(); return File( new FileStream(filePath, FileMode.Open), "application/octet-stream" , fileName); } |
方法二:
strFileName这个是下载下来的文件显示的名称,strToPath + targetFileName 这个是文件所在路径及其物理文件名(一般是字母加数字组合起来的)
调用:WebFile.downloadByStream(Response, strFileName, strToPath + targetFileName);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public static void downloadByStream(HttpResponse Response, string fileName, string filePath) { if (File.Exists(filePath)) { //以字符流的形式下载文件 FileStream fs = new FileStream(filePath, FileMode.Open); byte [] bytes = new byte [( int )fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); Response.ContentType = "application/octet-stream" ; //通知浏览器下载文件而不是打开 Response.AddHeader( "Content-Disposition" , "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); Response.BinaryWrite(bytes); Response.Flush(); Response.End(); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库