在C#中上传文件时,可以使用HttpClient类来发送form-data请求。以下是一些技巧:
使用MultipartFormDataContent类来构建form-data请求体,将文件添加到Content中:MultipartFormDataContent form = new MultipartFormDataContent();form.Add(new ByteArrayContent(File.ReadAllBytes(filePath)), "file", Path.GetFileName(filePath));设置HttpClient的请求头为"multipart/form-data":HttpClient client = new HttpClient();client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));发送POST请求并获取响应:HttpResponseMessage response = await client.PostAsync(url, form);string responseBody = await response.Content.ReadAsStringAsync();处理响应结果,例如检查是否上传成功:if (response.IsSuccessStatusCode){ Console.WriteLine("File uploaded successfully");}else{ Console.WriteLine("File upload failed");}通过以上技巧,可以在C#中实现文件上传功能并处理上传结果。


