c#webapi大文件下载接口
时间: 2024-10-22 13:12:45 浏览: 42
在 C# 中,创建一个支持大文件下载的 Web API 接口通常涉及到分块传输(Chunked Transfer Encoding)和文件流处理。这里是一个简单的示例,如何设计这个接口:
```csharp
using System.IO;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class FileDownloadController : ControllerBase
{
[HttpGet]
public IActionResult DownloadFile(string fileId)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
string filePath = "path_to_your_file/" + fileId; // 替换为实际文件路径
try
{
if (!System.IO.File.Exists(filePath))
{
return NotFound($"File with ID {fileId} not found.");
}
// 设置响应头信息,启用分块传输
Response.Headers.Add("Content-Disposition", $"attachment; filename={Path.GetFileName(filePath)}");
Response.Headers.Add("Accept-Ranges", "bytes");
// 使用FileStreamResult返回大文件
var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
using (fileStream)
{
var rangeHeader = Request.Headers["Range"];
long startByte = -1;
long endByte = -1;
// 解析范围请求
if (!string.IsNullOrEmpty(rangeHeader) && rangeHeader.StartsWith("bytes="))
{
string[] ranges = rangeHeader.Split('-');
startByte = long.Parse(ranges[0].Substring(6)) * 1024;
if (ranges.Length > 1)
endByte = long.Parse(ranges[1]) * 1024;
}
// 如果没有范围请求,则从头开始
if (startByte == -1)
{
startByte = 0;
endByte = fileStream.Length - 1;
}
fileStream.Seek(startByte, SeekOrigin.Begin);
byte[] buffer = new byte[4096]; // 分块大小,可根据网络状况调整
int bytesRead;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0 && (endByte == -1 || fileStream.Position < endByte))
{
Response.ContentLength = bytesRead;
Response.WriteAsync(buffer, 0, bytesRead);
}
}
return Ok();
}
catch (Exception ex)
{
return StatusCode((int)HttpStatusCode.InternalServerError, ex.Message);
}
}
}
```
阅读全文