基于net6的文件下载

1.文件下载接口

[HttpGet]
public IActionResult getLog()
{
    string fileName = "log.txt";   

    string fullPath = $"{Yourdir}/{fileName}";

    if (!System.IO.File.Exists(fullPath))
    {
        return NotFound("File not found.");
    }

    // Get file content as a stream
    var fileStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read);

    // Set the appropriate MIME type (application/octet-stream for binary data)
    var contentType = "application/oct-stream";

    // Return file stream with content type and file name for download
    return File(fileStream, contentType, fileName);
}

2.接口调用

 // The download function
    public async Task DownloadFileAsync(string fileUrl, string destinationPath, Action<int> progressCallback = null)
    {
        try
        {
            using (HttpClient client = new HttpClient())
            {
                // Send HTTP GET request
                using (HttpResponseMessage response = await client.GetAsync(fileUrl, HttpCompletionOption.ResponseHeadersRead))
                {
                    response.EnsureSuccessStatusCode(); // Throw if not a success code.

                    // Get the total file size (in case you want to show progress)
                    long? totalBytes = response.Content.Headers.ContentLength;

                    // Create the file stream for saving the downloaded file
                    using (Stream contentStream = await response.Content.ReadAsStreamAsync(),
                                  fileStream = new FileStream(destinationPath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
                    {
                        // Buffer for reading chunks of the file
                        byte[] buffer = new byte[8192];
                        long totalBytesRead = 0;
                        int bytesRead;

                        while ((bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
                        {
                            await fileStream.WriteAsync(buffer, 0, bytesRead);
                            totalBytesRead += bytesRead;

                            if (totalBytes.HasValue && progressCallback != null)
                            {
                                // Report progress as a percentage (if the file size is known)
                                int progressPercentage = (int)((totalBytesRead * 100L) / totalBytes.Value);
                                progressCallback(progressPercentage);
                            }
                        }
                    }
                }
            }

            Console.WriteLine("File downloaded successfully.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值