.NET 6 文件下载:使用 HttpResponse.WriteFileAsync 打包本地文件
在 .NET 6 中,可以使用 'HttpResponse' 对象的 'WriteFileAsync' 方法将本地文件打包并下载到客户端。以下是一个示例代码:
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Threading.Tasks;
public class HomeController : Controller
{
public async Task<IActionResult> DownloadFile()
{
// 本地文件路径
string filePath = "C:\path\to\file.txt";
// 检查文件是否存在
if (!System.IO.File.Exists(filePath))
{
return NotFound();
}
// 获取文件名
string fileName = Path.GetFileName(filePath);
// 打开文件流
var fileStream = new FileStream(filePath, FileMode.Open);
// 设置响应头,指定文件类型和下载文件名
HttpContext.Response.ContentType = "application/octet-stream";
HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=" + fileName);
// 写入文件流到响应中
await fileStream.CopyToAsync(HttpContext.Response.Body);
// 关闭文件流和响应
fileStream.Close();
await HttpContext.Response.Body.FlushAsync();
return Ok();
}
}
在上面的示例代码中,首先检查本地文件是否存在。如果文件不存在,则返回 404 错误。然后,获取文件名并打开文件流。接下来,设置响应头,指定文件类型为 'application/octet-stream',并将 'Content-Disposition' 标头设置为 'attachment',这将告诉浏览器下载文件而不是在浏览器中打开它。最后,将文件流写入响应流中,并在完成后关闭文件流和响应。
在控制器或路由中调用 'DownloadFile' 方法时,将触发文件下载。
原文地址: https://www.cveoy.top/t/topic/p35K 著作权归作者所有。请勿转载和采集!