C# HttpClient 4.5 multipart/form-data upload










99















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



I couldn't find any examples on the internet.










share|improve this question



















  • 1





    I try'd but i haven't any idea how to start it.. where i add the byteArray to the content and so on. i need kind of a start help.

    – ident
    May 7 '13 at 10:27











  • You can look this post answer. (With Proxy settings) stackoverflow.com/a/50462636/2123797

    – Ergin Çelik
    May 22 '18 at 8:04















99















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



I couldn't find any examples on the internet.










share|improve this question



















  • 1





    I try'd but i haven't any idea how to start it.. where i add the byteArray to the content and so on. i need kind of a start help.

    – ident
    May 7 '13 at 10:27











  • You can look this post answer. (With Proxy settings) stackoverflow.com/a/50462636/2123797

    – Ergin Çelik
    May 22 '18 at 8:04













99












99








99


47






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



I couldn't find any examples on the internet.










share|improve this question
















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



I couldn't find any examples on the internet.







c# upload .net-4.5 multipartform-data dotnet-httpclient






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 4 '16 at 18:07









derekerdmann

12.5k85799




12.5k85799










asked May 7 '13 at 10:19









identident

1,715298




1,715298







  • 1





    I try'd but i haven't any idea how to start it.. where i add the byteArray to the content and so on. i need kind of a start help.

    – ident
    May 7 '13 at 10:27











  • You can look this post answer. (With Proxy settings) stackoverflow.com/a/50462636/2123797

    – Ergin Çelik
    May 22 '18 at 8:04












  • 1





    I try'd but i haven't any idea how to start it.. where i add the byteArray to the content and so on. i need kind of a start help.

    – ident
    May 7 '13 at 10:27











  • You can look this post answer. (With Proxy settings) stackoverflow.com/a/50462636/2123797

    – Ergin Çelik
    May 22 '18 at 8:04







1




1





I try'd but i haven't any idea how to start it.. where i add the byteArray to the content and so on. i need kind of a start help.

– ident
May 7 '13 at 10:27





I try'd but i haven't any idea how to start it.. where i add the byteArray to the content and so on. i need kind of a start help.

– ident
May 7 '13 at 10:27













You can look this post answer. (With Proxy settings) stackoverflow.com/a/50462636/2123797

– Ergin Çelik
May 22 '18 at 8:04





You can look this post answer. (With Proxy settings) stackoverflow.com/a/50462636/2123797

– Ergin Çelik
May 22 '18 at 8:04












6 Answers
6






active

oldest

votes


















120














my result 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(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.net/images/d*/w*.[a-z]3").Value : null;









share|improve this answer




















  • 3





    Wow, it's so much simpler to do this when uploading big files to REST API. I don't like to comment for thanks, but thanks. It's portable for Windows Phone 8.

    – Léon Pelletier
    Jun 25 '13 at 8:50







  • 37





    Be aware, HttpClient is meant to be reused as much as possible within your application. Wrapping it with a using statement is considered a bad practice. This has been documented on many blog posts and books. Here is my favorite reading on the subject: chimera.labs.oreilly.com/books/1234000001708/ch14.html

    – Mauricio Aviles
    Sep 1 '16 at 7:14







  • 1





    This code failed for me as the boundary string passed to new MultipartFormDataContent(...) contained an invalid boundary character (maybe the "/" separator). No errors, just no files posted into the server - in my case, Context.Request.Files.Count = 0 in API controller. Possibly just a Nancy issue, but I suggest using something like DateTime.Now.Ticks.ToString("x") instead.

    – Dunc
    Sep 4 '17 at 12:41






  • 5





    @MauricioAviles, your link is broken. I found this one which explained it nicely: aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong

    – Kevin Harker
    Aug 11 '18 at 18:05


















68














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



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);



(You can requestContent.Add() whatever you want, take a look at the HttpContent descendant to see available types to pass in)



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






share|improve this answer























  • thanks, i solved this problem a week before your post, but thank you anyway..

    – ident
    May 16 '13 at 19:32











  • why image.jpg??

    – Toolkit
    Jun 12 '15 at 3:14






  • 1





    Ahhh thanks for the // here you can specify boundary if you need---^ :)

    – sfarbota
    Sep 10 '15 at 7:14






  • 1





    why this not works? public async Task<string> SendImage(byte foto) var requestContent = new MultipartFormDataContent(); var imageContent = new ByteArrayContent(foto); imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg"); requestContent.Add(imageContent, "foto", "foto.jpg"); string url = "myAddress/myWS/api/Home/SendImage?foto="; await _client.PostAsync(url, requestContent); return "ok";

    – atapi19
    Jan 29 '18 at 14:59







  • 1





    async on the first line and await on the line before the last are unnecessary.

    – 1valdis
    Apr 2 '18 at 23:08


















40














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



Here's my example. Hope it helps:



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:B2BAssetRootfiles596086596086.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:B2BAssetRootfiles596090596090.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();








share|improve this answer




















  • 7





    @Trout You have no idea how your code made me sooo happy today! +1

    – Pinch
    Jun 1 '15 at 18:41







  • 5





    This is the complete the answer.

    – V K
    Sep 13 '16 at 10:37






  • 1





    I know we're not supposed to comment a thank you note. But this right here is the best code I've seen on how to use MultipartFormDataContent. Kudos to you sir

    – sebagomez
    Oct 4 '16 at 15:24











  • Agreed. This is the only answer that include json string and file as part of the payload content.

    – frostshoxx
    Feb 27 '18 at 22:34











  • I test on my computer(win7 sp1, IIS 7.5) without Content-Type and Content-Disposition is Ok, but on Server 2008 R2(IIS 7.5) can't find files, it's strange. So I do as the answer.

    – chengzi
    Mar 28 '18 at 1:35


















8














Here's a complete sample that worked for me. The boundary value in the request is added automatically by .NET.



var url = "http://localhost/api/v1/yourendpointhere";
var filePath = @"C:pathtoimage.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;





share|improve this answer























  • How can we send a token with this? See this please: stackoverflow.com/questions/48295877/…

    – user9046719
    Jan 17 '18 at 15:36











  • Bad practice to load all data in memory before sending ...

    – Softlion
    Apr 20 '18 at 6:24











  • @Softlion - I am having trouble NOT loading it into memory before sending. If you know a better way, please post here: stackoverflow.com/questions/52446969/…

    – emery.noel
    Sep 21 '18 at 17:09


















3














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.g. a JPG) and additional API parameters. The file is directly uploaded from local disk via FileStream.



See here for the full example including additional API specific logic.



public static async Task UploadFileAsync(string token, string path, string channels)

// we need to send 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 file and directly upload it
FileStream fs = File.OpenRead(path);
multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(path));

// send request to API
var url = "https://slack.com/api/files.upload";
var response = await client.PostAsync(url, multiForm);






share|improve this answer






























    1














    Try this its working for me.



    private static async Task<object> Upload(string actionUrl)

    Image newImage = Image.FromFile(@"Absolute Path of image");
    ImageConverter _imageConverter = new ImageConverter();
    byte paramFileStream= (byte)_imageConverter.ConvertTo(newImage, typeof(byte));

    var formContent = new MultipartFormDataContent

    //send form text values here
    new StringContent("value1"),"key1",
    new StringContent("value2"),"key2" ,
    // send 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();

    return response;






    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f16416601%2fc-sharp-httpclient-4-5-multipart-form-data-upload%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      6 Answers
      6






      active

      oldest

      votes








      6 Answers
      6






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      120














      my result 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(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.net/images/d*/w*.[a-z]3").Value : null;









      share|improve this answer




















      • 3





        Wow, it's so much simpler to do this when uploading big files to REST API. I don't like to comment for thanks, but thanks. It's portable for Windows Phone 8.

        – Léon Pelletier
        Jun 25 '13 at 8:50







      • 37





        Be aware, HttpClient is meant to be reused as much as possible within your application. Wrapping it with a using statement is considered a bad practice. This has been documented on many blog posts and books. Here is my favorite reading on the subject: chimera.labs.oreilly.com/books/1234000001708/ch14.html

        – Mauricio Aviles
        Sep 1 '16 at 7:14







      • 1





        This code failed for me as the boundary string passed to new MultipartFormDataContent(...) contained an invalid boundary character (maybe the "/" separator). No errors, just no files posted into the server - in my case, Context.Request.Files.Count = 0 in API controller. Possibly just a Nancy issue, but I suggest using something like DateTime.Now.Ticks.ToString("x") instead.

        – Dunc
        Sep 4 '17 at 12:41






      • 5





        @MauricioAviles, your link is broken. I found this one which explained it nicely: aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong

        – Kevin Harker
        Aug 11 '18 at 18:05















      120














      my result 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(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.net/images/d*/w*.[a-z]3").Value : null;









      share|improve this answer




















      • 3





        Wow, it's so much simpler to do this when uploading big files to REST API. I don't like to comment for thanks, but thanks. It's portable for Windows Phone 8.

        – Léon Pelletier
        Jun 25 '13 at 8:50







      • 37





        Be aware, HttpClient is meant to be reused as much as possible within your application. Wrapping it with a using statement is considered a bad practice. This has been documented on many blog posts and books. Here is my favorite reading on the subject: chimera.labs.oreilly.com/books/1234000001708/ch14.html

        – Mauricio Aviles
        Sep 1 '16 at 7:14







      • 1





        This code failed for me as the boundary string passed to new MultipartFormDataContent(...) contained an invalid boundary character (maybe the "/" separator). No errors, just no files posted into the server - in my case, Context.Request.Files.Count = 0 in API controller. Possibly just a Nancy issue, but I suggest using something like DateTime.Now.Ticks.ToString("x") instead.

        – Dunc
        Sep 4 '17 at 12:41






      • 5





        @MauricioAviles, your link is broken. I found this one which explained it nicely: aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong

        – Kevin Harker
        Aug 11 '18 at 18:05













      120












      120








      120







      my result 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(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.net/images/d*/w*.[a-z]3").Value : null;









      share|improve this answer















      my result 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(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.net/images/d*/w*.[a-z]3").Value : null;










      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Sep 19 '13 at 19:44









      Shawn

      1,25543869




      1,25543869










      answered May 16 '13 at 19:35









      identident

      1,715298




      1,715298







      • 3





        Wow, it's so much simpler to do this when uploading big files to REST API. I don't like to comment for thanks, but thanks. It's portable for Windows Phone 8.

        – Léon Pelletier
        Jun 25 '13 at 8:50







      • 37





        Be aware, HttpClient is meant to be reused as much as possible within your application. Wrapping it with a using statement is considered a bad practice. This has been documented on many blog posts and books. Here is my favorite reading on the subject: chimera.labs.oreilly.com/books/1234000001708/ch14.html

        – Mauricio Aviles
        Sep 1 '16 at 7:14







      • 1





        This code failed for me as the boundary string passed to new MultipartFormDataContent(...) contained an invalid boundary character (maybe the "/" separator). No errors, just no files posted into the server - in my case, Context.Request.Files.Count = 0 in API controller. Possibly just a Nancy issue, but I suggest using something like DateTime.Now.Ticks.ToString("x") instead.

        – Dunc
        Sep 4 '17 at 12:41






      • 5





        @MauricioAviles, your link is broken. I found this one which explained it nicely: aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong

        – Kevin Harker
        Aug 11 '18 at 18:05












      • 3





        Wow, it's so much simpler to do this when uploading big files to REST API. I don't like to comment for thanks, but thanks. It's portable for Windows Phone 8.

        – Léon Pelletier
        Jun 25 '13 at 8:50







      • 37





        Be aware, HttpClient is meant to be reused as much as possible within your application. Wrapping it with a using statement is considered a bad practice. This has been documented on many blog posts and books. Here is my favorite reading on the subject: chimera.labs.oreilly.com/books/1234000001708/ch14.html

        – Mauricio Aviles
        Sep 1 '16 at 7:14







      • 1





        This code failed for me as the boundary string passed to new MultipartFormDataContent(...) contained an invalid boundary character (maybe the "/" separator). No errors, just no files posted into the server - in my case, Context.Request.Files.Count = 0 in API controller. Possibly just a Nancy issue, but I suggest using something like DateTime.Now.Ticks.ToString("x") instead.

        – Dunc
        Sep 4 '17 at 12:41






      • 5





        @MauricioAviles, your link is broken. I found this one which explained it nicely: aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong

        – Kevin Harker
        Aug 11 '18 at 18:05







      3




      3





      Wow, it's so much simpler to do this when uploading big files to REST API. I don't like to comment for thanks, but thanks. It's portable for Windows Phone 8.

      – Léon Pelletier
      Jun 25 '13 at 8:50






      Wow, it's so much simpler to do this when uploading big files to REST API. I don't like to comment for thanks, but thanks. It's portable for Windows Phone 8.

      – Léon Pelletier
      Jun 25 '13 at 8:50





      37




      37





      Be aware, HttpClient is meant to be reused as much as possible within your application. Wrapping it with a using statement is considered a bad practice. This has been documented on many blog posts and books. Here is my favorite reading on the subject: chimera.labs.oreilly.com/books/1234000001708/ch14.html

      – Mauricio Aviles
      Sep 1 '16 at 7:14






      Be aware, HttpClient is meant to be reused as much as possible within your application. Wrapping it with a using statement is considered a bad practice. This has been documented on many blog posts and books. Here is my favorite reading on the subject: chimera.labs.oreilly.com/books/1234000001708/ch14.html

      – Mauricio Aviles
      Sep 1 '16 at 7:14





      1




      1





      This code failed for me as the boundary string passed to new MultipartFormDataContent(...) contained an invalid boundary character (maybe the "/" separator). No errors, just no files posted into the server - in my case, Context.Request.Files.Count = 0 in API controller. Possibly just a Nancy issue, but I suggest using something like DateTime.Now.Ticks.ToString("x") instead.

      – Dunc
      Sep 4 '17 at 12:41





      This code failed for me as the boundary string passed to new MultipartFormDataContent(...) contained an invalid boundary character (maybe the "/" separator). No errors, just no files posted into the server - in my case, Context.Request.Files.Count = 0 in API controller. Possibly just a Nancy issue, but I suggest using something like DateTime.Now.Ticks.ToString("x") instead.

      – Dunc
      Sep 4 '17 at 12:41




      5




      5





      @MauricioAviles, your link is broken. I found this one which explained it nicely: aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong

      – Kevin Harker
      Aug 11 '18 at 18:05





      @MauricioAviles, your link is broken. I found this one which explained it nicely: aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong

      – Kevin Harker
      Aug 11 '18 at 18:05













      68














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



      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);



      (You can requestContent.Add() whatever you want, take a look at the HttpContent descendant to see available types to pass in)



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






      share|improve this answer























      • thanks, i solved this problem a week before your post, but thank you anyway..

        – ident
        May 16 '13 at 19:32











      • why image.jpg??

        – Toolkit
        Jun 12 '15 at 3:14






      • 1





        Ahhh thanks for the // here you can specify boundary if you need---^ :)

        – sfarbota
        Sep 10 '15 at 7:14






      • 1





        why this not works? public async Task<string> SendImage(byte foto) var requestContent = new MultipartFormDataContent(); var imageContent = new ByteArrayContent(foto); imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg"); requestContent.Add(imageContent, "foto", "foto.jpg"); string url = "myAddress/myWS/api/Home/SendImage?foto="; await _client.PostAsync(url, requestContent); return "ok";

        – atapi19
        Jan 29 '18 at 14:59







      • 1





        async on the first line and await on the line before the last are unnecessary.

        – 1valdis
        Apr 2 '18 at 23:08















      68














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



      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);



      (You can requestContent.Add() whatever you want, take a look at the HttpContent descendant to see available types to pass in)



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






      share|improve this answer























      • thanks, i solved this problem a week before your post, but thank you anyway..

        – ident
        May 16 '13 at 19:32











      • why image.jpg??

        – Toolkit
        Jun 12 '15 at 3:14






      • 1





        Ahhh thanks for the // here you can specify boundary if you need---^ :)

        – sfarbota
        Sep 10 '15 at 7:14






      • 1





        why this not works? public async Task<string> SendImage(byte foto) var requestContent = new MultipartFormDataContent(); var imageContent = new ByteArrayContent(foto); imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg"); requestContent.Add(imageContent, "foto", "foto.jpg"); string url = "myAddress/myWS/api/Home/SendImage?foto="; await _client.PostAsync(url, requestContent); return "ok";

        – atapi19
        Jan 29 '18 at 14:59







      • 1





        async on the first line and await on the line before the last are unnecessary.

        – 1valdis
        Apr 2 '18 at 23:08













      68












      68








      68







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



      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);



      (You can requestContent.Add() whatever you want, take a look at the HttpContent descendant to see available types to pass in)



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






      share|improve this answer













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



      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);



      (You can requestContent.Add() whatever you want, take a look at the HttpContent descendant to see available types to pass in)



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







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered May 15 '13 at 11:03









      WDRustWDRust

      3,0321523




      3,0321523












      • thanks, i solved this problem a week before your post, but thank you anyway..

        – ident
        May 16 '13 at 19:32











      • why image.jpg??

        – Toolkit
        Jun 12 '15 at 3:14






      • 1





        Ahhh thanks for the // here you can specify boundary if you need---^ :)

        – sfarbota
        Sep 10 '15 at 7:14






      • 1





        why this not works? public async Task<string> SendImage(byte foto) var requestContent = new MultipartFormDataContent(); var imageContent = new ByteArrayContent(foto); imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg"); requestContent.Add(imageContent, "foto", "foto.jpg"); string url = "myAddress/myWS/api/Home/SendImage?foto="; await _client.PostAsync(url, requestContent); return "ok";

        – atapi19
        Jan 29 '18 at 14:59







      • 1





        async on the first line and await on the line before the last are unnecessary.

        – 1valdis
        Apr 2 '18 at 23:08

















      • thanks, i solved this problem a week before your post, but thank you anyway..

        – ident
        May 16 '13 at 19:32











      • why image.jpg??

        – Toolkit
        Jun 12 '15 at 3:14






      • 1





        Ahhh thanks for the // here you can specify boundary if you need---^ :)

        – sfarbota
        Sep 10 '15 at 7:14






      • 1





        why this not works? public async Task<string> SendImage(byte foto) var requestContent = new MultipartFormDataContent(); var imageContent = new ByteArrayContent(foto); imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg"); requestContent.Add(imageContent, "foto", "foto.jpg"); string url = "myAddress/myWS/api/Home/SendImage?foto="; await _client.PostAsync(url, requestContent); return "ok";

        – atapi19
        Jan 29 '18 at 14:59







      • 1





        async on the first line and await on the line before the last are unnecessary.

        – 1valdis
        Apr 2 '18 at 23:08
















      thanks, i solved this problem a week before your post, but thank you anyway..

      – ident
      May 16 '13 at 19:32





      thanks, i solved this problem a week before your post, but thank you anyway..

      – ident
      May 16 '13 at 19:32













      why image.jpg??

      – Toolkit
      Jun 12 '15 at 3:14





      why image.jpg??

      – Toolkit
      Jun 12 '15 at 3:14




      1




      1





      Ahhh thanks for the // here you can specify boundary if you need---^ :)

      – sfarbota
      Sep 10 '15 at 7:14





      Ahhh thanks for the // here you can specify boundary if you need---^ :)

      – sfarbota
      Sep 10 '15 at 7:14




      1




      1





      why this not works? public async Task<string> SendImage(byte foto) var requestContent = new MultipartFormDataContent(); var imageContent = new ByteArrayContent(foto); imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg"); requestContent.Add(imageContent, "foto", "foto.jpg"); string url = "myAddress/myWS/api/Home/SendImage?foto="; await _client.PostAsync(url, requestContent); return "ok";

      – atapi19
      Jan 29 '18 at 14:59






      why this not works? public async Task<string> SendImage(byte foto) var requestContent = new MultipartFormDataContent(); var imageContent = new ByteArrayContent(foto); imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg"); requestContent.Add(imageContent, "foto", "foto.jpg"); string url = "myAddress/myWS/api/Home/SendImage?foto="; await _client.PostAsync(url, requestContent); return "ok";

      – atapi19
      Jan 29 '18 at 14:59





      1




      1





      async on the first line and await on the line before the last are unnecessary.

      – 1valdis
      Apr 2 '18 at 23:08





      async on the first line and await on the line before the last are unnecessary.

      – 1valdis
      Apr 2 '18 at 23:08











      40














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



      Here's my example. Hope it helps:



      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:B2BAssetRootfiles596086596086.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:B2BAssetRootfiles596090596090.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();








      share|improve this answer




















      • 7





        @Trout You have no idea how your code made me sooo happy today! +1

        – Pinch
        Jun 1 '15 at 18:41







      • 5





        This is the complete the answer.

        – V K
        Sep 13 '16 at 10:37






      • 1





        I know we're not supposed to comment a thank you note. But this right here is the best code I've seen on how to use MultipartFormDataContent. Kudos to you sir

        – sebagomez
        Oct 4 '16 at 15:24











      • Agreed. This is the only answer that include json string and file as part of the payload content.

        – frostshoxx
        Feb 27 '18 at 22:34











      • I test on my computer(win7 sp1, IIS 7.5) without Content-Type and Content-Disposition is Ok, but on Server 2008 R2(IIS 7.5) can't find files, it's strange. So I do as the answer.

        – chengzi
        Mar 28 '18 at 1:35















      40














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



      Here's my example. Hope it helps:



      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:B2BAssetRootfiles596086596086.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:B2BAssetRootfiles596090596090.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();








      share|improve this answer




















      • 7





        @Trout You have no idea how your code made me sooo happy today! +1

        – Pinch
        Jun 1 '15 at 18:41







      • 5





        This is the complete the answer.

        – V K
        Sep 13 '16 at 10:37






      • 1





        I know we're not supposed to comment a thank you note. But this right here is the best code I've seen on how to use MultipartFormDataContent. Kudos to you sir

        – sebagomez
        Oct 4 '16 at 15:24











      • Agreed. This is the only answer that include json string and file as part of the payload content.

        – frostshoxx
        Feb 27 '18 at 22:34











      • I test on my computer(win7 sp1, IIS 7.5) without Content-Type and Content-Disposition is Ok, but on Server 2008 R2(IIS 7.5) can't find files, it's strange. So I do as the answer.

        – chengzi
        Mar 28 '18 at 1:35













      40












      40








      40







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



      Here's my example. Hope it helps:



      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:B2BAssetRootfiles596086596086.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:B2BAssetRootfiles596090596090.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();








      share|improve this answer















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



      Here's my example. Hope it helps:



      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:B2BAssetRootfiles596086596086.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:B2BAssetRootfiles596090596090.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();









      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited May 21 '15 at 14:27









      Steve Trout

      8,16011226




      8,16011226










      answered Jan 30 '15 at 18:36









      Johnny ChuJohnny Chu

      56953




      56953







      • 7





        @Trout You have no idea how your code made me sooo happy today! +1

        – Pinch
        Jun 1 '15 at 18:41







      • 5





        This is the complete the answer.

        – V K
        Sep 13 '16 at 10:37






      • 1





        I know we're not supposed to comment a thank you note. But this right here is the best code I've seen on how to use MultipartFormDataContent. Kudos to you sir

        – sebagomez
        Oct 4 '16 at 15:24











      • Agreed. This is the only answer that include json string and file as part of the payload content.

        – frostshoxx
        Feb 27 '18 at 22:34











      • I test on my computer(win7 sp1, IIS 7.5) without Content-Type and Content-Disposition is Ok, but on Server 2008 R2(IIS 7.5) can't find files, it's strange. So I do as the answer.

        – chengzi
        Mar 28 '18 at 1:35












      • 7





        @Trout You have no idea how your code made me sooo happy today! +1

        – Pinch
        Jun 1 '15 at 18:41







      • 5





        This is the complete the answer.

        – V K
        Sep 13 '16 at 10:37






      • 1





        I know we're not supposed to comment a thank you note. But this right here is the best code I've seen on how to use MultipartFormDataContent. Kudos to you sir

        – sebagomez
        Oct 4 '16 at 15:24











      • Agreed. This is the only answer that include json string and file as part of the payload content.

        – frostshoxx
        Feb 27 '18 at 22:34











      • I test on my computer(win7 sp1, IIS 7.5) without Content-Type and Content-Disposition is Ok, but on Server 2008 R2(IIS 7.5) can't find files, it's strange. So I do as the answer.

        – chengzi
        Mar 28 '18 at 1:35







      7




      7





      @Trout You have no idea how your code made me sooo happy today! +1

      – Pinch
      Jun 1 '15 at 18:41






      @Trout You have no idea how your code made me sooo happy today! +1

      – Pinch
      Jun 1 '15 at 18:41





      5




      5





      This is the complete the answer.

      – V K
      Sep 13 '16 at 10:37





      This is the complete the answer.

      – V K
      Sep 13 '16 at 10:37




      1




      1





      I know we're not supposed to comment a thank you note. But this right here is the best code I've seen on how to use MultipartFormDataContent. Kudos to you sir

      – sebagomez
      Oct 4 '16 at 15:24





      I know we're not supposed to comment a thank you note. But this right here is the best code I've seen on how to use MultipartFormDataContent. Kudos to you sir

      – sebagomez
      Oct 4 '16 at 15:24













      Agreed. This is the only answer that include json string and file as part of the payload content.

      – frostshoxx
      Feb 27 '18 at 22:34





      Agreed. This is the only answer that include json string and file as part of the payload content.

      – frostshoxx
      Feb 27 '18 at 22:34













      I test on my computer(win7 sp1, IIS 7.5) without Content-Type and Content-Disposition is Ok, but on Server 2008 R2(IIS 7.5) can't find files, it's strange. So I do as the answer.

      – chengzi
      Mar 28 '18 at 1:35





      I test on my computer(win7 sp1, IIS 7.5) without Content-Type and Content-Disposition is Ok, but on Server 2008 R2(IIS 7.5) can't find files, it's strange. So I do as the answer.

      – chengzi
      Mar 28 '18 at 1:35











      8














      Here's a complete sample that worked for me. The boundary value in the request is added automatically by .NET.



      var url = "http://localhost/api/v1/yourendpointhere";
      var filePath = @"C:pathtoimage.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;





      share|improve this answer























      • How can we send a token with this? See this please: stackoverflow.com/questions/48295877/…

        – user9046719
        Jan 17 '18 at 15:36











      • Bad practice to load all data in memory before sending ...

        – Softlion
        Apr 20 '18 at 6:24











      • @Softlion - I am having trouble NOT loading it into memory before sending. If you know a better way, please post here: stackoverflow.com/questions/52446969/…

        – emery.noel
        Sep 21 '18 at 17:09















      8














      Here's a complete sample that worked for me. The boundary value in the request is added automatically by .NET.



      var url = "http://localhost/api/v1/yourendpointhere";
      var filePath = @"C:pathtoimage.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;





      share|improve this answer























      • How can we send a token with this? See this please: stackoverflow.com/questions/48295877/…

        – user9046719
        Jan 17 '18 at 15:36











      • Bad practice to load all data in memory before sending ...

        – Softlion
        Apr 20 '18 at 6:24











      • @Softlion - I am having trouble NOT loading it into memory before sending. If you know a better way, please post here: stackoverflow.com/questions/52446969/…

        – emery.noel
        Sep 21 '18 at 17:09













      8












      8








      8







      Here's a complete sample that worked for me. The boundary value in the request is added automatically by .NET.



      var url = "http://localhost/api/v1/yourendpointhere";
      var filePath = @"C:pathtoimage.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;





      share|improve this answer













      Here's a complete sample that worked for me. The boundary value in the request is added automatically by .NET.



      var url = "http://localhost/api/v1/yourendpointhere";
      var filePath = @"C:pathtoimage.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;






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered May 8 '17 at 20:31









      nthpixelnthpixel

      1,65221835




      1,65221835












      • How can we send a token with this? See this please: stackoverflow.com/questions/48295877/…

        – user9046719
        Jan 17 '18 at 15:36











      • Bad practice to load all data in memory before sending ...

        – Softlion
        Apr 20 '18 at 6:24











      • @Softlion - I am having trouble NOT loading it into memory before sending. If you know a better way, please post here: stackoverflow.com/questions/52446969/…

        – emery.noel
        Sep 21 '18 at 17:09

















      • How can we send a token with this? See this please: stackoverflow.com/questions/48295877/…

        – user9046719
        Jan 17 '18 at 15:36











      • Bad practice to load all data in memory before sending ...

        – Softlion
        Apr 20 '18 at 6:24











      • @Softlion - I am having trouble NOT loading it into memory before sending. If you know a better way, please post here: stackoverflow.com/questions/52446969/…

        – emery.noel
        Sep 21 '18 at 17:09
















      How can we send a token with this? See this please: stackoverflow.com/questions/48295877/…

      – user9046719
      Jan 17 '18 at 15:36





      How can we send a token with this? See this please: stackoverflow.com/questions/48295877/…

      – user9046719
      Jan 17 '18 at 15:36













      Bad practice to load all data in memory before sending ...

      – Softlion
      Apr 20 '18 at 6:24





      Bad practice to load all data in memory before sending ...

      – Softlion
      Apr 20 '18 at 6:24













      @Softlion - I am having trouble NOT loading it into memory before sending. If you know a better way, please post here: stackoverflow.com/questions/52446969/…

      – emery.noel
      Sep 21 '18 at 17:09





      @Softlion - I am having trouble NOT loading it into memory before sending. If you know a better way, please post here: stackoverflow.com/questions/52446969/…

      – emery.noel
      Sep 21 '18 at 17:09











      3














      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.g. a JPG) and additional API parameters. The file is directly uploaded from local disk via FileStream.



      See here for the full example including additional API specific logic.



      public static async Task UploadFileAsync(string token, string path, string channels)

      // we need to send 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 file and directly upload it
      FileStream fs = File.OpenRead(path);
      multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(path));

      // send request to API
      var url = "https://slack.com/api/files.upload";
      var response = await client.PostAsync(url, multiForm);






      share|improve this answer



























        3














        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.g. a JPG) and additional API parameters. The file is directly uploaded from local disk via FileStream.



        See here for the full example including additional API specific logic.



        public static async Task UploadFileAsync(string token, string path, string channels)

        // we need to send 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 file and directly upload it
        FileStream fs = File.OpenRead(path);
        multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(path));

        // send request to API
        var url = "https://slack.com/api/files.upload";
        var response = await client.PostAsync(url, multiForm);






        share|improve this answer

























          3












          3








          3







          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.g. a JPG) and additional API parameters. The file is directly uploaded from local disk via FileStream.



          See here for the full example including additional API specific logic.



          public static async Task UploadFileAsync(string token, string path, string channels)

          // we need to send 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 file and directly upload it
          FileStream fs = File.OpenRead(path);
          multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(path));

          // send request to API
          var url = "https://slack.com/api/files.upload";
          var response = await client.PostAsync(url, multiForm);






          share|improve this answer













          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.g. a JPG) and additional API parameters. The file is directly uploaded from local disk via FileStream.



          See here for the full example including additional API specific logic.



          public static async Task UploadFileAsync(string token, string path, string channels)

          // we need to send 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 file and directly upload it
          FileStream fs = File.OpenRead(path);
          multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(path));

          // send request to API
          var url = "https://slack.com/api/files.upload";
          var response = await client.PostAsync(url, multiForm);







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 13 '18 at 15:57









          Erik KalkokenErik Kalkoken

          13.4k32553




          13.4k32553





















              1














              Try this its working for me.



              private static async Task<object> Upload(string actionUrl)

              Image newImage = Image.FromFile(@"Absolute Path of image");
              ImageConverter _imageConverter = new ImageConverter();
              byte paramFileStream= (byte)_imageConverter.ConvertTo(newImage, typeof(byte));

              var formContent = new MultipartFormDataContent

              //send form text values here
              new StringContent("value1"),"key1",
              new StringContent("value2"),"key2" ,
              // send 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();

              return response;






              share|improve this answer





























                1














                Try this its working for me.



                private static async Task<object> Upload(string actionUrl)

                Image newImage = Image.FromFile(@"Absolute Path of image");
                ImageConverter _imageConverter = new ImageConverter();
                byte paramFileStream= (byte)_imageConverter.ConvertTo(newImage, typeof(byte));

                var formContent = new MultipartFormDataContent

                //send form text values here
                new StringContent("value1"),"key1",
                new StringContent("value2"),"key2" ,
                // send 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();

                return response;






                share|improve this answer



























                  1












                  1








                  1







                  Try this its working for me.



                  private static async Task<object> Upload(string actionUrl)

                  Image newImage = Image.FromFile(@"Absolute Path of image");
                  ImageConverter _imageConverter = new ImageConverter();
                  byte paramFileStream= (byte)_imageConverter.ConvertTo(newImage, typeof(byte));

                  var formContent = new MultipartFormDataContent

                  //send form text values here
                  new StringContent("value1"),"key1",
                  new StringContent("value2"),"key2" ,
                  // send 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();

                  return response;






                  share|improve this answer















                  Try this its working for me.



                  private static async Task<object> Upload(string actionUrl)

                  Image newImage = Image.FromFile(@"Absolute Path of image");
                  ImageConverter _imageConverter = new ImageConverter();
                  byte paramFileStream= (byte)_imageConverter.ConvertTo(newImage, typeof(byte));

                  var formContent = new MultipartFormDataContent

                  //send form text values here
                  new StringContent("value1"),"key1",
                  new StringContent("value2"),"key2" ,
                  // send 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();

                  return response;







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 7 '18 at 13:50









                  EstevaoLuis

                  1,19952030




                  1,19952030










                  answered Nov 7 '18 at 13:21









                  Vishnu KumarVishnu Kumar

                  213




                  213



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f16416601%2fc-sharp-httpclient-4-5-multipart-form-data-upload%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

                      Crossroads (UK TV series)

                      ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế