using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
public class FileUploader
{
private readonly HttpClient _httpClient;
public FileUploader(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task UploadFileAsync(string filePath, string uploadUrl, int maxRetries = 3, TimeSpan? retryDelay = null)
{
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
var formContent = new MultipartFormDataContent();
var streamContent = new StreamContent(fileStream);
formContent.Add(streamContent, "file", Path.GetFileName(filePath));
for (int i = 0; i < maxRetries; i++)
{
try
{
await _httpClient.PostAsync(uploadUrl, formContent);
return; // 上传成功,退出方法
}
catch (Exception ex)
{
if (i == maxRetries - 1) // 最后一次尝试
{
throw; // 抛出异常通知调用者
}
// 等待一段时间后重试
await Task.Delay(retryDelay ?? TimeSpan.FromSeconds(Math.Pow(2, i)));
}
}
}
}
}
// 使用示例
// 假设你已经有了一个配置好的HttpClient实例
// HttpClient client = new HttpClient();
// FileUploader uploader = new FileUploader(client);
// await uploader.UploadFileAsync("path/to/your/file.txt", "http://yourserver/upload");
上传错误处理和重试机制
最新推荐文章于 2024-09-09 17:03:46 发布