如何在ASP.NET Core中检测文件下载完成 [英] How to detect file download completion in ASP.NET Core

查看:288
本文介绍了如何在ASP.NET Core中检测文件下载完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Controller类中具有以下代码:

I have the following code in my Controller class:

[HttpPost]
public async Task<IActionResult> GetDataFile(string id, [FromBody] DataLog log)
{
   FileStream fileStream = System.IO.File.OpenRead($"{dataFile}_{id}.log");
   //using a using block or Close prevents the download...
   return File(fileStream, "application/octet-stream");
}

该文件应该是临时存在的,因此当客户端完成下载后,服务器应删除该文件.

The file should exist temporarily, so when the client finished with the download, the server should delete the file.

我知道流打开时无法关闭它.

I know that while the stream is open, I can't close it.

我应该使用什么回调?有最佳实践吗?

What callback should I use? Is there a best practice for this?

推荐答案

您可以执行以下操作:

public FileResult GetDataFile(string id, [FromBody] DataLog log)
{
    var bytes = System.IO.File.ReadAllBytes("<absolute path of file here>");
    System.IO.File.Delete("<absolute path of file here>");
    return File(bytes, "application/octet-stream", "<name of file>");
}

因此,您正在将文件读入字节数组,然后删除物理文件并将字节数组返回给客户端.

So, you are reading the file into the byte array, then deleting the physical file and returning the byte array to the client.

这篇关于如何在ASP.NET Core中检测文件下载完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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