美文网首页
.netcore c# web api 文件下载慢的解决办法

.netcore c# web api 文件下载慢的解决办法

作者: StormerX | 来源:发表于2019-08-27 20:31 被阅读0次

一开始我在初始化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);
            }
        }

相关文章

网友评论

      本文标题:.netcore c# web api 文件下载慢的解决办法

      本文链接:https://www.haomeiwen.com/subject/gylyectx.html