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();
Uploading multipart form files with HttpClient
First, it's important to note that a 500 response is akin to an unhandled exception, i.e. it's a bug on their end and more or less impossible to know for sure what you did wrong. I would suggest reporting it to them and, although I'm not familiar with Support Bee, I would hope they have good support people who can help you troubleshoot. :)
But if you want to play the guessing game, I agree that subtle differences between your successful Postman call and your code are a good place to start. For that header, note that content
is the MultipartFormDataContent
. You actually want to set it on the StreamContent
object.
Also, look at the request headers Postman is sending and see if Content-Disposition
includes a filename
. You might need to add that to your code too, if the API is expecting it.
Here's how to do both:
var fileContent = new StreamContent(File.OpenRead(path));
fileContent.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
content.Add(fileContent, "files[]", Path.GetFileName(path));
If that's not the problem, look at the "raw" version of the request body in Postman, as well as those 11 request headers, and see if you can spot anything else you might be missing.
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.
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 httpclient upload csv service
I went the route of using Postman to create my request, then got the generated code for C# with the RestSharp NuGet Package.
public static void UploadFile(FileInfo file, Token token, DateTime lwt, DateTime nwt)
{
string status = "";
string reason = "";
try
{
var client = new RestClient(token.Url);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddParameter("key", token.Key);
request.AddParameter("uuid", token.Uuid);
request.AddParameter("context", token.Context);
request.AddFile("file", file.FullName);
IRestResponse response = client.Execute(request);
status = response.StatusCode.ToString();
reason = response.ErrorMessage.ToString();
Library.RecordUploadSuccess(file, lwt, nwt);
}
catch (Exception ex)
{
Library.RecordUploadError(file, status, reason);
//Library.RecordUploadError(file, ex.Message, ex.StackTrace);
}
}
Highly recommend going that route for multipart form-data.
Related Topics
Webbrowser Control in a New Thread
Mvvm: Tutorial from Start to Finish
Generating All Possible Combinations
.Net String.Format() to Add Commas in Thousands Place For a Number
How to Get All Child Controls of a Windows Forms Form of a Specific Type (Button/Textbox)
Decimal VS Double! - Which One Should I Use and When
Convert List≪Derivedclass≫ to List≪Baseclass≫
How to Limit the Amount of Concurrent Async I/O Operations
C# Interfaces. Implicit Implementation Versus Explicit Implementation
How to Create a Custom Authorizeattribute in ASP.NET Core
Process.Start: How to Get the Output
What Does the =≫ Operator Mean in a Property
Generating HTML Email Body in C#
How to Parse a Json String That Would Cause Illegal C# Identifiers