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();
    }
}                                               

  

posted @   小严不言慢  阅读(565)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示