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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM