How to Send a File and Form Data with Httpclient in C#

C# HttpClient 4.5 multipart/form-data upload

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

Using C# HttpClient to POST File without multipart/form-data

I think it would look something like this

using var client = new HttpClient();

var file = File.ReadAllBytes(filePath);

var content = new ByteArrayContent(file);
content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

var result = await client.PostAsync(uploadURI.ToString(), content);
result.EnsureSuccessStatusCode();

var response = await result.Content.ReadAsStringAsync();
var doc = JsonDocument.Parse(response);

return doc.RootElement.GetProperty("documentId").ToString();

Send form-data in C# HttpClient

You're sending your data in an incorrect way by using FormUrlEncodedContent.

To send your parameters as MultipartFormDataContent string values you need to replace the code below:

var dataContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("key1", "myvalue1"),
new KeyValuePair<string, string>("key2", "myvalue2"),
new KeyValuePair<string, string>("key3", "myvalue3")
});

With this:

content.Add(new StringContent("myvalue1"), "key1");
content.Add(new StringContent("myvalue2"), "key2");
content.Add(new StringContent("myvalue3"), "key3");

HttpClient Multipart Form Post in C#

So the problem I'm seeing is that the MultipartFormDataContent request message will always set the content type of the request to "multipart/form-data". Endcoding json and placing that into the request only "looks" like to the model binder as a string.

Your options are:

  • have your mvc action method receive a string and deserialize into your object
  • post each property of your model as a form part
  • create a custom model binder that will handle your request.
  • Breakup the operation into two posts, first sends the json metadata, the other sends the file. The response from the server should send some id or key to correlate the two requests.

Reading through the RFC document and the MSDN documentation you may be able to do this, if you replace MultipartFormDataContent with MultipartContent. But I have not tested this yet.

HTTP POST multipart/formdata using HttpClient

You need to add stream.Seek(0, SeekOrigin.Begin); in order to jump back to the beginning of the MemoryStream. You should also use CopyToAsync

In the second version, you had a fresh MemoryStream from the byte[] array, which is positioned on 0 anyway.

using var formContent = new MultipartFormDataContent("NKdKd9Yk");
using var stream = new MemoryStream();
await file.CopyToAsync(stream);
stream.Seek(0, SeekOrigin.Begin);
formContent.Headers.ContentType.MediaType = "multipart/form-data";
formContent.Add(new StreamContent(stream), "file", fileName);
using var response = await httpClient.PostAsync(GetDocumentUpdateRelativeUrl(), formContent);

Although to be honest, the MemoryStream seems entirely unnecessary here. Just pass the a Stream from file directly.

using var formContent = new MultipartFormDataContent("NKdKd9Yk");
formContent.Headers.ContentType.MediaType = "multipart/form-data";
using var stream = file.OpenReadStream();
formContent.Add(new StreamContent(stream), "file", fileName);
using var response = await httpClient.PostAsync(GetDocumentUpdateRelativeUrl(), formContent);

Httpclient multipart/form-data pust image

Is it necessary to send the filename and mimetype via multipart-formdata? If not try to send the data as StreamContent and set the filename and mime type via the content header:

private static HttpResponseMessage Upload()
{
var apiUri = string.Format(url);
string url = (url);

var message = new HttpRequestMessage();
message.RequestUri = new Uri(apiUri);
message.Method = HttpMethod.Put;

var fileObj = Images.ChooseImageAndToInfoObject();

using (var client = new HttpClient())

var filestream = new FileStream(fileObj.filePath, FileMode.Open);

var content = new StreamContent(filestream);
content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(fileObj.filePath));
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "\"files\"",
FileName = "\"" + fileName + "\""
};

message.Content = content;

message.Headers.Add("Authorization", MyToken);

// var res = client.SendAsync(message).Result;
var response = client.PutAsync(url, content).Result;
return response;

Send the content via PUT if you set the file to a specific id or via Post:

var response = client.PostAsync(url, content).Result;

C# Multipart form-data in HttpClient Post REST API

All, Finally i am able to reproduce the Postman code in C# programmatically.

I able to add the "metadata" property in the multipart form-data.

Reference: Upload Files Using HttpClient

string Seshat_URL = "https://azr-stg.dev03.abs.ase.southcentralus.us.wc.net/files/v11";
using (var multiPartStream = new MultipartFormDataContent())
{

multiPartStream.Add(new StringContent("{}"), "metadata");
multiPartStream.Add(new ByteArrayContent(filecontent, 0, filecontent.Length), "file", docName);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, Seshat_URL);
request.Content = multiPartStream;
//"application/json" - content type
request.Headers.Accept.Add(JSON_GENERIC_MEDIA_TYPE);
request.Headers.Add("X-Client-Id", ClientId);
request.Headers.Add("Tenant-Id", TenantId);

HttpCompletionOption option = HttpCompletionOption.ResponseContentRead;
System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);

using (HttpResponseMessage response = _httpClient.SendAsync(request, option).Result)
{
if (response.IsSuccessStatusCode)
{
var deserializedObject = JsonConvert.DeserializeObject<Wc.MCM.UIMVC.Helpers1.BlobResponse>(response.Content.ReadAsStringAsync().Result);
return deserializedObject.fileId.ToString();
}
}

}//End Try


Related Topics



Leave a reply



Submit