internal static async Task<string> UploadFile(string filePath, Dictionary<string, string> parameters, Action<int, string, bool, string> action) { string res = ""; string fileName = Path.GetFileName(filePath); try { //await httpClient.UploadFileAsync("/uploadbigfile", new FileInfo(filepath)); //using var handler = new HttpClientHandler(); //using var progressMessageHandler = new ProgressMessageHandler(); //注册进度事件 //progressMessageHandler.HttpSendProgress += (object sender, HttpProgressEventArgs e) => //{ // action(Convert.ToInt32(e.ProgressPercentage), fileName, false, "正在上传"); //}; ProgressMessageHandler progressMessageHandler = new ProgressMessageHandler(); progressMessageHandler.HttpSendProgress += (s, e) => { action(Convert.ToInt32(e.ProgressPercentage), fileName, false, "正在上传"); }; using var handler = new SocketsHttpHandler { AutomaticDecompression = DecompressionMethods.All, MaxConnectionsPerServer = Environment.ProcessorCount * 2, // 根据CPU核心数动态调整 PooledConnectionIdleTimeout = TimeSpan.FromMinutes(2), PooledConnectionLifetime = TimeSpan.FromMinutes(3), EnableMultipleHttp2Connections = true, AllowAutoRedirect = false, MaxResponseHeadersLength = 131072, // 增大响应头缓冲区 默认值 65536 ConnectTimeout = TimeSpan.FromSeconds(60), // 单独控制连接阶段超时 ResponseDrainTimeout = TimeSpan.FromSeconds(180), // 响应数据读取超时 }; // 显式创建处理器链 var handlerChain = new DelegatingHandler[] { progressMessageHandler }; using (var client = System.Net.Http.HttpClientFactory.Create(handler, handlerChain)) //using (var client = new HttpClient(progressMessageHandler)) { client.MaxResponseContentBufferSize = int.MaxValue; client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower; client.DefaultRequestVersion = HttpVersion.Version11; client.Timeout = TimeSpan.FromMinutes(5); client.DefaultRequestHeaders.ConnectionClose = false; using (var content = new MultipartFormDataContent()) { try { // 创建一个文件流和进度报告流 using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); //using var memoryStream = Program.MemoryManager.GetStream("FileUpload"); //using (var progressStream = new ProgressStream(fileStream, (bytesRead, totalBytes) => //{ // // 这里更新上传进度 // double progress = (double)bytesRead / totalBytes * 100; // Console.WriteLine($"Upload progress: {progress:F2}%"); // action(Convert.ToInt32(progress), false, "正在上传"); //})) var streamContent = new StreamContent(fileStream); //await fileStream.CopyToAsync(memoryStream); //memoryStream.Position = 0; //var streamContent = new StreamContent(memoryStream); streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); content.Add(streamContent, "file", fileName); foreach (var item in parameters) { content.Add(new StringContent(item.Value), item.Key); } // await streamContent.CopyToAsync(new ProgressStream(content.Add(streamContent, "file", Path.GetFileName(filePath)), progress), 8192, CancellationToken.None); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, SystemConfig.baseUrl + SystemConfig.UpladUrl); // 设置请求头 request.Headers.Add("Authorization", SystemConfig.Authorization); request.Headers.Add("Accept", "*/*"); // 增加兼容头 // var content = new StringContent("{xmbh:WDDHXDFJ,XDLMCID:5003,XDLMSID:1111,XKLX:tykg,XAction:GetDataInterface}", Encoding.UTF8, "application/json"); request.Content = content; // 发送POST请求 HttpResponseMessage response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); // 读取响应内容 var responseContent = await response.Content.ReadAsStringAsync(); Console.WriteLine("Response: " + responseContent); action(100, fileName, true, "上传完成"); res = responseContent; } catch (Exception ex) { action(0, fileName, false, ex.Message); Log.Error(ex, $"{res} | 消息:{ex.Message}"); return res; //action(0, false, ex.Message); //throw new Exception(ex.Message); } } } } catch (Exception ex) { action(0, fileName, false, ex.Message); Log.Error(ex, $"{res} | 消息:{ex.Message}"); return res; // action(0, false, ex.Message); //throw new Exception(ex.Message); } return res; } 上传文件后服务器返回 {StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Cache-Control: private
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Access-Control-Allow-Headers: Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, Authorization,Accept
Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 600
Date: Wed, 24 Dec 2025 03:18:37 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 5433
}} 客户端使用net8 服务端为net4.0
最新发布