banner



Apache Jersey Client Multipart Upload Mp4 As Octet-stream?

C# HttpClient 4.5 multipart/grade-data upload

  • Abode
  • Question
  • C# HttpClient 4.5 multipart/form-information upload

Does anyone know how to use the HttpClient in .Net 4.5 with multipart/class-data upload?

I couldn't detect any examples on the internet.

This question is tagged with c# upload .net-4.5 multipartform-data dotnet-httpclient

~ Asked on 2013-05-07 10:xix:11

10 Answers


my effect looks like this:

              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(epitome)), "bilddatei", "upload.jpg");                using (                  var message =                      expect client.PostAsync("http://world wide web.directupload.net/index.php?mode=upload", content))               {                   var input = await bulletin.Content.ReadAsStringAsync();                    render !string.IsNullOrWhiteSpace(input) ? Regex.Match(input, @"http://\w*\.directupload\.internet/images/\d*/\westward*\.[a-z]{3}").Value : null;               }           }      } }                          

~ Answered on 2013-05-16 19:35:41


It works more or less like this (example using an image/jpg file):

              async public Task<HttpResponseMessage> UploadImage(cord url, byte[] ImageData) {     var requestContent = new MultipartFormDataContent();      //    here you tin can specify boundary if y'all need---^     var imageContent = new ByteArrayContent(ImageData);     imageContent.Headers.ContentType =          MediaTypeHeaderValue.Parse("paradigm/jpeg");      requestContent.Add(imageContent, "image", "epitome.jpg");      return look customer.PostAsync(url, requestContent); }                          

(You tin requestContent.Add() whatever yous want, take a await at the HttpContent descendant to meet bachelor types to pass in)

When completed, you'll detect the response content inside HttpResponseMessage.Content that yous can consume with HttpContent.ReadAs*Async.

~ Answered on 2013-05-15 11:03:42


This is an instance of how to post string and file stream with HTTPClient using MultipartFormDataContent. The Content-Disposition and Content-Blazon demand to be specified for each HTTPContent:

Hither'southward my instance. Hope information technology helps:

              individual 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.one.mp4";              cord assetName = Path.GetFileName(path);              var request = new HTTPBrightCoveRequest()                 {                     Method = "create_video",                     Parameters = new Params()                         {                             CreateMultipleRenditions = "truthful",                             EncodeTo = EncodeTo.Mp4.ToString().ToUpper(),                             Token = "x8sLalfXacgn-4CzhTBm7uaCxVAPjvKqTf1oXpwLVYYoCkejZUsYtg..",                             Video = new Video()                                 {                                     Name = assetName,                                     ReferenceId = Guid.NewGuid().ToString(),                                     ShortDescription = assetName                                 }                         }                 };              //Content-Disposition: form-information; proper name="json"             var stringContent = new StringContent(JsonConvert.SerializeObject(request));             stringContent.Headers.Add("Content-Disposition", "form-information; proper noun=\"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.ane.mp4";             streamContent.Headers.Add("Content-Disposition", "class-information; proper name=\"file\"; filename=\"" + Path.GetFileName(path) + "\"");             content.Add together(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();             Panel.WriteLine(input.Result);             Console.Read();         }     } }                          

~ Answered on 2015-01-thirty 18:36:49


Here is another example on how to use HttpClient to upload a multipart/form-data.

It uploads a file to a REST API and includes the file itself (e.thou. a JPG) and additional API parameters. The file is directly uploaded from local disk via FileStream.

Come across here for the full case including boosted API specific logic.

              public static async Task UploadFileAsync(string token, cord path, string channels) {     // we need to ship a request with multipart/form-data     var multiForm = new MultipartFormDataContent();      // add API method parameters     multiForm.Add(new StringContent(token), "token");     multiForm.Add(new StringContent(channels), "channels");      // add together file and directly upload it     FileStream fs = File.OpenRead(path);     multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(path));      // ship request to API     var url = "https://slack.com/api/files.upload";     var response = await customer.PostAsync(url, multiForm); }                          

~ Answered on 2018-11-thirteen 15:57:58


Try this its working for me.

              individual static async Task<object> Upload(cord actionUrl) {     Image newImage = Image.FromFile(@"Accented Path of prototype");     ImageConverter _imageConverter = new ImageConverter();     byte[] paramFileStream= (byte[])_imageConverter.ConvertTo(newImage, typeof(byte[]));      var formContent = new MultipartFormDataContent     {         // Send class text values hither         {new StringContent("value1"),"key1"},         {new StringContent("value2"),"key2" },         // Ship Image Here         {new StreamContent(new MemoryStream(paramFileStream)),"imagekey","filename.jpg"}     };      var myHttpClient = new HttpClient();     var response = await myHttpClient.PostAsync(actionUrl.ToString(), formContent);     string stringContent = await response.Content.ReadAsStringAsync();      render response; }                          

~ Answered on 2018-11-07 xiii:21:03


Here'southward a complete sample that worked for me. The purlieus value in the request is added automatically past .NET.

              var url = "http://localhost/api/v1/yourendpointhere"; var filePath = @"C:\path\to\image.jpg";  HttpClient httpClient = new HttpClient(); MultipartFormDataContent grade = new MultipartFormDataContent();  FileStream fs = File.OpenRead(filePath); var streamContent = new StreamContent(fs);  var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Effect); imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/class-data");  form.Add(imageContent, "epitome", Path.GetFileName(filePath)); var response = httpClient.PostAsync(url, form).Result;                          

~ Answered on 2017-05-08 twenty:31:12


Example with preloader Dotnet 3.0 Cadre

              ProgressMessageHandler processMessageHander = new ProgressMessageHandler();  processMessageHander.HttpSendProgress += (southward, e) => {     if (e.ProgressPercentage > 0)     {         ProgressPercentage = eastward.ProgressPercentage;         TotalBytes = e.TotalBytes;         progressAction?.Invoke(progressFile);     } };  using (var client = HttpClientFactory.Create(processMessageHander)) {     var uri = new Uri(transfer.BackEndUrl);     client.DefaultRequestHeaders.Authorization =     new AuthenticationHeaderValue("Bearer", AccessToken);      using (MultipartFormDataContent multiForm = new MultipartFormDataContent())     {         multiForm.Add(new StringContent(FileId), "FileId");         multiForm.Add together(new StringContent(FileName), "FileName");         string hash = "";          using (MD5 md5Hash = MD5.Create())         {             var sb = new StringBuilder();             foreach (var data in md5Hash.ComputeHash(File.ReadAllBytes(FullName)))             {                 sb.Append(data.ToString("x2"));             }             hash = event.ToString();         }         multiForm.Add(new StringContent(hash), "Hash");          using (FileStream fs = File.OpenRead(FullName))         {             multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(FullName));             var response = expect client.PostAsync(uri, multiForm);             progressFile.Message = response.ToString();              if (response.IsSuccessStatusCode) {                 progressAction?.Invoke(progressFile);             } else {                 progressErrorAction?.Invoke(progressFile);             }             response.EnsureSuccessStatusCode();         }     } }                          

~ Answered on 2019-12-12 16:x:48


              X509Certificate clientKey1 = nada; clientKey1 = new X509Certificate(AppSetting["certificatePath"], AppSetting["pswd"]); cord url = "https://EndPointAddress"; FileStream fs = File.OpenRead(FilePath); var streamContent = new StreamContent(fs);  var FileContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result); FileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("ContentType"); var handler = new WebRequestHandler();   handler.ClientCertificateOptions = ClientCertificateOption.Transmission; handler.ClientCertificates.Add(clientKey1); handler.ServerCertificateValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) => {     return true; };   using (var client = new HttpClient(handler)) {     // Post it     HttpResponseMessage httpResponseMessage = client.PostAsync(url, FileContent).Event;      if (!httpResponseMessage.IsSuccessStatusCode)     {         string ss = httpResponseMessage.StatusCode.ToString();     } }                          

~ Answered on 2019-09-20 12:47:36


I'one thousand adding a lawmaking snippet which shows on how to post a file to an API which has been exposed over DELETE http verb. This is not a common instance to upload a file with DELETE http verb but it is allowed. I've assumed Windows NTLM authentication for authorizing the phone call.

The problem that one might face is that all the overloads of HttpClient.DeleteAsync method take no parameters for HttpContent the way we get it in PostAsync method

              var requestUri = new Uri("http://UrlOfTheApi"); using (var streamToPost = new MemoryStream("C:\temp.txt")) using (var fileStreamContent = new StreamContent(streamToPost)) using (var httpClientHandler = new HttpClientHandler() { UseDefaultCredentials = true }) using (var httpClient = new HttpClient(httpClientHandler, true)) using (var requestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri)) using (var formDataContent = new MultipartFormDataContent()) {     formDataContent.Add(fileStreamContent, "myFile", "temp.txt");     requestMessage.Content = formDataContent;     var response = httpClient.SendAsync(requestMessage).GetAwaiter().GetResult();      if (response.IsSuccessStatusCode)     {         // File upload was successfull     }     else     {         var erroResult = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();         throw new Exception("Error on the server : " + erroResult);     } }                          

You need below namespaces at the top of your C# file:

              using Organization; using System.Net; using System.IO; using Arrangement.Net.Http;                          

P.S. Lamentable well-nigh so many using blocks(IDisposable blueprint) in my code. Unfortunately, the syntax of using construct of C# doesn't support initializing multiple variables in single argument.

~ Answered on 2019-09-28 09:thirteen:30


              public async Task<object> PassImageWithText(IFormFile files) {     byte[] data;     cord effect = "";     ByteArrayContent bytes;      MultipartFormDataContent multiForm = new MultipartFormDataContent();      try     {         using (var client = new HttpClient())         {             using (var br = new BinaryReader(files.OpenReadStream()))             {                 data = br.ReadBytes((int)files.OpenReadStream().Length);             }              bytes = new ByteArrayContent(information);             multiForm.Add(bytes, "files", files.FileName);             multiForm.Add(new StringContent("value1"), "key1");             multiForm.Add(new StringContent("value2"), "key2");              var res = await client.PostAsync(_MEDIA_ADD_IMG_URL, multiForm);         }     }     take hold of (Exception e)     {         throw new Exception(due east.ToString());     }      return result; }                          

~ Answered on 2019-08-11 15:ten:39


Source: https://syntaxfix.com/question/17246/c-httpclient-4-5-multipart-form-data-upload

Posted by: richardsonnabowle2002.blogspot.com

0 Response to "Apache Jersey Client Multipart Upload Mp4 As Octet-stream?"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel