C# HttpClient 4.5 multipart/form-data upload
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
add a comment |
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
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
add a comment |
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
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
c# upload .net-4.5 multipartform-data dotnet-httpclient
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
add a comment |
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
add a comment |
6 Answers
6
active
oldest
votes
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;
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 ausing
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 tonew 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 aNancy
issue, but I suggest using something likeDateTime.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
add a comment |
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
.
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 andawait
on the line before the last are unnecessary.
– 1valdis
Apr 2 '18 at 23:08
|
show 2 more comments
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();
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 useMultipartFormDataContent
. 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) withoutContent-Type
andContent-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
add a comment |
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;
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
add a comment |
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);
add a comment |
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;
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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;
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 ausing
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 tonew 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 aNancy
issue, but I suggest using something likeDateTime.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
add a comment |
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;
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 ausing
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 tonew 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 aNancy
issue, but I suggest using something likeDateTime.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
add a comment |
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;
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;
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 ausing
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 tonew 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 aNancy
issue, but I suggest using something likeDateTime.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
add a comment |
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 ausing
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 tonew 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 aNancy
issue, but I suggest using something likeDateTime.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
add a comment |
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
.
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 andawait
on the line before the last are unnecessary.
– 1valdis
Apr 2 '18 at 23:08
|
show 2 more comments
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
.
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 andawait
on the line before the last are unnecessary.
– 1valdis
Apr 2 '18 at 23:08
|
show 2 more comments
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
.
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
.
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 andawait
on the line before the last are unnecessary.
– 1valdis
Apr 2 '18 at 23:08
|
show 2 more comments
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 andawait
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
|
show 2 more comments
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();
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 useMultipartFormDataContent
. 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) withoutContent-Type
andContent-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
add a comment |
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();
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 useMultipartFormDataContent
. 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) withoutContent-Type
andContent-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
add a comment |
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();
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();
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 useMultipartFormDataContent
. 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) withoutContent-Type
andContent-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
add a comment |
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 useMultipartFormDataContent
. 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) withoutContent-Type
andContent-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
add a comment |
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;
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
add a comment |
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;
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
add a comment |
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;
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;
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
add a comment |
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
add a comment |
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);
add a comment |
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);
add a comment |
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);
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);
answered Nov 13 '18 at 15:57
Erik KalkokenErik Kalkoken
13.4k32553
13.4k32553
add a comment |
add a comment |
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;
add a comment |
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;
add a comment |
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;
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;
edited Nov 7 '18 at 13:50
EstevaoLuis
1,19952030
1,19952030
answered Nov 7 '18 at 13:21
Vishnu KumarVishnu Kumar
213
213
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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