输出硬盘文件,提供下载

///<summary>
       
/// 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
       
/// </summary>
       
/// <param name="MyRequest">Page.Request对象</param>
       
/// <param name="MyResponse">Page.Response对象</param>
       
/// <param name="MyFileName">下载文件名</param>
       
/// <param name="MyFullPath">带文件名下载路径</param>
       
/// <param name="MySpeed">每秒允许下载的字节数</param>
       
/// <returns>True Or False</returns>
        public bool ResponseFile(HttpRequest MyRequest, HttpResponse MyResponse, string MyFileName, string MyFullPath, long MySpeed)
        {
           
try
            {
                FileStream myFile
= new FileStream(MyFullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                BinaryReader br
= new BinaryReader(myFile);

               
try
                {
                    MyResponse.AddHeader(
"Accept-Ranges", "bytes");
                    MyResponse.Buffer
= false;

                   
long fileLength = myFile.Length;
                   
long startBytes = 0;
                   
int pack = 10240;     //10K bytes
                    int sleep = (int)Math.Floor(1000.0 * pack / MySpeed) + 1;

                   
if (MyRequest.Headers["Range"] != null)
                    {
                        MyResponse.StatusCode
= 206;
                       
string[] range = MyRequest.Headers["Range"].Split(new char[] { '=', '-' });
                        startBytes
= Convert.ToInt64(range[1]);
                    }

                    MyResponse.AddHeader(
"Content-Length", (fileLength - startBytes).ToString());

                   
if ((startBytes != 0))
                    {
                        MyResponse.AddHeader(
"Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                    }

                    MyResponse.AddHeader(
"Connection", "Keep-Alive");
                    MyResponse.ContentType
= "application/octet-stream";
                    MyResponse.AddHeader(
"Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(MyFileName, System.Text.Encoding.UTF8));
                    br.BaseStream.Seek(startBytes, SeekOrigin.Begin);

                   
int maxCount = (int)Math.Floor(1.0 * (fileLength - startBytes) / pack) + 1;

                   
for (int i = 0; i <= maxCount; i++)
                    {
                       
if ((MyResponse.IsClientConnected))
                        {
                            MyResponse.BinaryWrite(br.ReadBytes(pack));
                            System.Threading.Thread.Sleep(sleep);
                        }
                       
else
                        {
                            i
= maxCount;
                        }
                    }
                }
               
catch
                {
                   
return false;
                }
               
finally
                {
                    br.Close(); myFile.Close();
                }
            }
           
catch
            {
               
return false;
            }
           
return true;
        }

备注:未测试

========================

在 ASP.NET Core 中,可以使用以下代码实现输出硬盘文件提供下载功能,并支持大文件、续传、速度限制和资源占用小: ```csharp public async Task<IActionResult> Download(string filePath) { var file = new FileInfo(filePath); if (!file.Exists) { return NotFound(); } var memory = new MemoryStream(); using (var stream = new FileStream(filePath, FileMode.Open)) { await stream.CopyToAsync(memory); } memory.Position = 0; var response = File(memory, GetContentType(filePath), file.Name); response.EnableRangeProcessing = true; response.FileDownloadName = file.Name; response.LastModified = file.LastWriteTimeUtc; response.EntityTag = new EntityTagHeaderValue("\"" + file.LastWriteTimeUtc.Ticks.ToString("x") + "\""); return response; } private string GetContentType(string path) { var provider = new FileExtensionContentTypeProvider(); if (!provider.TryGetContentType(path, out var contentType)) { contentType = "application/octet-stream"; } return contentType; } ``` 在上面的代码中,Download 方法用于输出指定路径的硬盘文件,使用 File 方法将文件流转换为文件下载响应,并启用了文件范围请求处理(Range Processing)。同时,还设置了文件下载名称、文件最后修改时间和实体标记(Entity Tag),以便浏览器可以正确处理文件下载请求。 值得注意的是,上述代码中使用了内存流(MemoryStream)而不是文件流(FileStream),这是为了避免在服务器上创建临时文件,从而减少资源占用。如果需要实现文件下载速度限制等高级功能,可以使用更复杂的技术,例如将文件分割为多个块并以一定的速率发送到客户端。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值