在 .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中文网其他相关文章!