asp.net core 文件的处理

1、获取文件的 MIME 类型:FileExtensionContentTypeProvider

参考:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1

2、从 .net core 程序中获取文件:IFileProvider

参考:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/file-providers?view=aspnetcore-3.1

3、从 Action 方法中返回文件结果:PhysicalFile

参考:https://stackoverflow.com/questions/53631178/invalidoperationexception-on-file-return

4、正确处理下载文件的HTTP头:ASP.NET 的 PhysicalFile 结果已经自动处理

参考:https://blog.robotshell.org/2012/deal-with-http-header-encoding-for-file-download/

https://www.cnblogs.com/brucejia/archive/2012/12/24/2831060.html

测试代码:

复制代码
[ApiController]
[Route("[controller]")]
public class DownloadController : Controller
{
    public DownloadController(IHostEnvironment environment, IFileProvider fileProvider)
    {
        HostEnvironment = environment;
        FileProvider = fileProvider;
    }

    IHostEnvironment HostEnvironment;

    IFileProvider FileProvider;

    [HttpGet]
    [Route("index")]
    public IActionResult Index(string filename)
    {
        var path = @"\temp\" + filename;

        // 检查文件存在
        var fileInfo = FileProvider.GetFileInfo(path);
        if (fileInfo.PhysicalPath == null)
        {
            return Content("文件不存在("+ HostEnvironment.ContentRootPath + "):" + filename);
        }

        // 检查文件类型
        FileExtensionContentTypeProvider provider = new FileExtensionContentTypeProvider();
        if (!provider.TryGetContentType(path, out string contentType))
        {
            return Content("未知的文件类型:" + fileInfo.PhysicalPath);
        }

        // 返回下载
        return Content($"文件路径:{fileInfo.PhysicalPath}, MIME:{contentType}。");
    }

    [HttpGet]
    [Route("file")]
    public IActionResult File(string filename)
    {
        var path = @"\temp\" + filename;

        // 检查文件存在
        var fileInfo = FileProvider.GetFileInfo(path);
        if (fileInfo.PhysicalPath == null)
        {
            return Content("文件不存在(" + HostEnvironment.ContentRootPath + "):" + filename);
        }

        // 检查文件类型
        FileExtensionContentTypeProvider provider = new FileExtensionContentTypeProvider();
        if (!provider.TryGetContentType(path, out string contentType))
        {
            return Content("未知的文件类型:" + filename);
        }

        // 返回下载
        return PhysicalFile(fileInfo.PhysicalPath, contentType, "这个是文件的下载名称.xlsx");
    }
}
复制代码

Startup.cs

复制代码
public class Startup
{
    public Startup(IConfiguration configuration, IHostEnvironment environment)
    {
        Configuration = configuration;
        HostEnvironment = environment;
    }

    public IConfiguration Configuration { get; }

    public IHostEnvironment HostEnvironment { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        // 文件提供程序
        // 参考文档:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/file-providers?view=aspnetcore-3.1

        var physicalProvider = HostEnvironment.ContentRootFileProvider;
        var embeddedProvider = new EmbeddedFileProvider(Assembly.GetEntryAssembly());
        var compositeProvider = new CompositeFileProvider(physicalProvider, embeddedProvider);

        services.AddSingleton<IFileProvider>(compositeProvider);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}
复制代码
posted @   不是豆豆  阅读(962)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
友情链接:迷途


点击右上角即可分享
微信分享提示