在ASP.NET Core中流式传输文件后如何删除文件 [英] How to delete a file after it was streamed in ASP.NET Core

查看:238
本文介绍了在ASP.NET Core中流式传输文件后如何删除文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在返回临时文件后删除它.如何使用ASP.NET Core做到这一点?

I would like to delete a temporary file after returning it form action. How can i achieve that with ASP.NET Core:

public IActionResult Download(long id)
{
    var file = "C:/temp/tempfile.zip";
    var fileName = "file.zip;
    return this.PhysicalFile(file, "application/zip", fileName);
    // I Would like to have File.Delete(file) here !!
}

文件太大,无法使用内存流返回.

The file is too big for returning using memory stream.

推荐答案

File() or PhysicalFile() return a FileResult-derived class that just delegates processing to an executor service. PhysicalFileResult's ExecuteResultAsync method calls :

var executor = context.HttpContext.RequestServices
                 .GetRequiredService<IActionResultExecutor<PhysicalFileResult>>();
return executor.ExecuteAsync(context, this);

所有其他基于FileResult的类都以类似的方式工作.

All other FileResult-based classes work in a similar way.

PhysicalFileResultExecutor a>类实际上是将文件的内容写入Response流.

The PhysicalFileResultExecutor class essentially writes the file's contents to the Response stream.

一种快速而肮脏的解决方案是创建您自己的基于 PhysicalFileResult 的类,该类委派给PhysicalFileResultExecutor,但在执行程序完成后删除该文件:

A quick and dirty solution would be to create your own PhysicalFileResult-based class that delegates to PhysicalFileResultExecutor but deletes the file once the executor finishes :

public class TempPhysicalFileResult : PhysicalFileResult
{
    public TempPhysicalFileResult(string fileName, string contentType)
                 : base(fileName, contentType) { }
    public TempPhysicalFileResult(string fileName, MediaTypeHeaderValue contentType)
                 : base(fileName, contentType) { }

    public override async  Task ExecuteResultAsync(ActionContext context)
    {
        await base.ExecuteResultAsync(context);
        File.Delete(FileName);
    }
}

代替调用 PhysicalFile()来创建 PhysicalFileResult ,您可以创建并返回 TempPhysicalFileResult ,例如:

Instead of calling PhysicalFile() to create the PhysicalFileResult you can create and return a TempPhysicalFileResult, eg :

return new TempPhysicalFileResult(file, "application/zip"){FileDownloadName=fileName};

这是同一件事PhysicalFile()可以:

[NonAction]
public virtual PhysicalFileResult PhysicalFile(
    string physicalPath,
    string contentType,
    string fileDownloadName)
    => new PhysicalFileResult(physicalPath, contentType) { FileDownloadName = fileDownloadName };

一种更复杂的解决方案是创建一个自定义执行器,该执行器负责压缩和清理文件,而动作代码不包含结果格式代码

A more sophisticated solution would be to create a custom executor that took care eg of compression as well as cleaning up files, leaving the action code clean of result formatting code

这篇关于在ASP.NET Core中流式传输文件后如何删除文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆