一开始我在初始化FileStream实例的时候只是简单写了2个参数:
new FileStream(path, FileMode.Open, FileAccess.Read);
后来使用的时候感觉下载速度好慢,之后修改如下,再测试下载速度正常了。
new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 65536, FileOptions.Asynchronous | FileOptions.SequentialScan));
完整代码
[HttpGet("{fileName}")]
public async Task<IActionResult> Download(string fileName)
{
try
{
if (string.IsNullOrEmpty(fileName))
{
return NotFound();
}
var path = $@"{hostingEnv.WebRootPath}UploadFiles/" + fileName;
var memoryStream = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 65536, FileOptions.Asynchronous | FileOptions.SequentialScan))
{
await stream.CopyToAsync(memoryStream);
}
memoryStream.Seek(0, SeekOrigin.Begin);
// 回傳檔案到 Client 需要附上 Content Type,否則瀏覽器會解析失敗。
return new FileStreamResult(memoryStream, _contentTypes[Path.GetExtension(path).ToLowerInvariant()]);
}
catch(Exception ex)
{
return Ok(ex.Message);
}
}
网友评论