在C#中上传文件时,可以使用HttpClient类来发送form-data请求。以下是一些技巧:
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(new ByteArrayContent(File.ReadAllBytes(filePath)), "file", Path.GetFileName(filePath));
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));
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#中实现文件上传功能并处理上传结果。