在 .NET 4.5 中使用 HttpClient 上傳多部分錶單數據
多部分錶單數據是將文件上傳到 Web 服務的常用方法。在 .NET 4.5 中,HttpClient 通過使用 MultipartFormDataContent 支持多部分錶單數據上傳。
代碼示例:
以下代碼片段演示瞭如何在 HttpClient 中使用多部分錶單數據上傳:
<code class="language-csharp">using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Globalization; using System.Text.RegularExpressions; public static async Task<string> UploadFileAsync(byte[] image) { using (var client = new HttpClient()) { using (var content = new MultipartFormDataContent($"Upload----{DateTime.Now.ToString(CultureInfo.InvariantCulture)}")) { content.Add(new StreamContent(new MemoryStream(image)), "bilddatei", "upload.jpg"); using (var response = await client.PostAsync("http://www.directupload.net/index.php?mode=upload", content)) { if (response.IsSuccessStatusCode) { var responseBody = await response.Content.ReadAsStringAsync(); var match = Regex.Match(responseBody, @"http://\w*\.directupload\.net/images/\d*/\w*\.[a-z]{3}"); return match.Success ? match.Value : null; } else { return null; // or handle error appropriately } } } } }</code>
This revised example includes error handling and uses more descriptive variable names for better readability. The regular expression remains the same, but the code is now more robust and easier to understand.
以上是如何在.NET 4.5中使用Multipart Form Data上載文件形式數據?的詳細內容。更多資訊請關注PHP中文網其他相關文章!