查看: 97|回复: 0

asp.net core 下载文件的教训

[复制链接]

4

主题

9

帖子

17

积分

新手上路

Rank: 1

积分
17
发表于 2023-6-18 15:48:24 | 显示全部楼层 |阅读模式

第一种方法:如果程序的根目录存在wwwroot目录
那么可以按照下面的方法下载文件
public Microsoft.AspNetCore.Mvc.FileResult DownLoadTemplate()
        {
//结果是 VirtualFileResult(如果不用默认的wwwroot,那么要初始化FileProvider属性)
            return File(
              "importmb222.xlsx", //这个文件在wwwroot目录下面
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
              $"importmb222.xlsx");
}
第二种方法:如果下载文件位于程序根目录(AppContext.BaseDirectory 和 Environment.CurrentDirectory路径不同,竟然都能检测到文件的存在),必须用PhysicalFile才行!!!
AppContext.BaseDirectory:D:\wyh3\bin\Debug\net7.0\
Environment.CurrentDirectory:D:\wyh3
var f1 = Path.Combine(AppContext.BaseDirectory, "importmb111.xlsx");//程序根目录,用这个
var f2 = Path.Combine(AppContext.BaseDirectory, "importmb222.xlsx");
var s1 = Path.Combine(Environment.CurrentDirectory, "importmb111.xlsx");//这个也行
var s2 = Path.Combine(Environment.CurrentDirectory, "importmb222.xlsx");

Console.WriteLine(System.IO.File.Exists(f1));//true
Console.WriteLine(System.IO.File.Exists(f2));//false
Console.WriteLine(System.IO.File.Exists(s1));//true
Console.WriteLine(System.IO.File.Exists(s2));//false

return PhysicalFile(
                FullFileName,
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                $"importmb2.xlsx");
有高人仔细研究了,详见下文
由ASP.NET Core根据路径下载文件异常引发的探究
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表