在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#中實現文件上傳功能并處理上傳結果。