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}");
}
}