Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Http MultipartFormDataContent

I have been asked to do the following in C#:

/**

* 1. Create a MultipartPostMethod

* 2. Construct the web URL to connect to the SDP Server

* 3. Add the filename to be attached as a parameter to the MultipartPostMethod with parameter name "filename"

* 4. Execute the MultipartPostMethod

* 5. Receive and process the response as required

* /

I have written some code that has no errors, however, the file is not attached.

Can someone have a look at my C# code to see if I have written the code incorrectly?

Here is my code:

var client = new HttpClient();
const string weblinkUrl = "http://testserver.com/attach?";
var method = new MultipartFormDataContent();
const string fileName = "C:\file.txt";
var streamContent = new StreamContent(File.Open(fileName, FileMode.Open));
method.Add(streamContent, "filename");

var result = client.PostAsync(weblinkUrl, method);
MessageBox.Show(result.Result.ToString());
like image 962
user2985419 Avatar asked Dec 02 '13 02:12

user2985419


People also ask

What is MultipartFormDataContent?

This type is derived from MultipartContent type. All MultipartFormDataContent does is provide methods to add required Content-Disposition headers to content object added to the collection.

How do you read MultipartFormDataContent?

Based on content type you can read it as a file or string. Example for string content type: var dataContents = request. Content as MultipartFormDataContent; foreach (var dataContent in dataContents) { var name = dataContent.Headers.ContentDisposition.Name; var value = dataContent.

What is Httpcontent?

A base class representing an HTTP entity body and content headers.

What is Formurlencodedcontent C#?

A container for name/value tuples encoded using application/x-www-form-urlencoded MIME type.


2 Answers

Posting MultipartFormDataContent in C# is simple but may be confusing the first time. Here is the code that works for me when posting a .png .txt etc.

// 2. Create the url 
string url = "https://myurl.com/api/...";
string filename = "myFile.png";
// In my case this is the JSON that will be returned from the post
string result = "";
// 1. Create a MultipartPostMethod
// "NKdKd9Yk" is the boundary parameter

using (var formContent = new MultipartFormDataContent("NKdKd9Yk"))
{
    formContent.Headers.ContentType.MediaType = "multipart/form-data";
    // 3. Add the filename C:\\... + fileName is the path your file
    Stream fileStream = System.IO.File.OpenRead("C:\\Users\\username\\Pictures\\" + fileName);
    formContent.Add(new StreamContent(fileStream), fileName, fileName);

    using (var client = new HttpClient())
    {
        // Bearer Token header if needed
        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + _bearerToken);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));

        try
        {
            // 4.. Execute the MultipartPostMethod
            var message = await client.PostAsync(url, formContent);
            // 5.a Receive the response
            result = await message.Content.ReadAsStringAsync();                
        }
        catch (Exception ex)
        {
            // Do what you want if it fails.
            throw ex;
        }
    }    
}

// 5.b Process the reponse Get a usable object from the JSON that is returned
MyObject myObject = JsonConvert.DeserializeObject<MyObject>(result);

In my case I need to do something with the object after it posts so I convert it to that object with JsonConvert.

like image 167
Braden Brown Avatar answered Oct 16 '22 14:10

Braden Brown


I debugged this the problem is here:

method.Add(streamContent, "filename");

This 'Add' doesn't actually put the file in the BODY of Multipart Content.

like image 2
A-Sharabiani Avatar answered Oct 16 '22 13:10

A-Sharabiani