Http MultipartFormDataContent

I was 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 wrote code that does not have errors, but the file is not connected.

Can someone look at my C # code to see if I wrote 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()); 
+15
c # post multipartform-data filestream
source share
4 answers

This has been asked several times on SO. Here are some possible solutions:

C # HttpClient 4.5 multipart / form-data upload: C # HttpClient 4.5 multipart / form-data upload

Publishing a multi-page HttpClient form in C #: Publishing a multi-page HttpClient form in C #

In a personal note, check the data sent in the request and check the response. Fiddler is great for this.

+10
source

I know this is an old post. But for those looking for a solution to give a more direct answer, here is what I found:

 using System.Diagnostics; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web; using System.Web.Http; public class UploadController : ApiController { public async Task<HttpResponseMessage> PostFormData() { // Check if the request contains multipart/form-data. if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string root = HttpContext.Current.Server.MapPath("~/App_Data"); var provider = new MultipartFormDataStreamProvider(root); try { // Read the form data. await Request.Content.ReadAsMultipartAsync(provider); // This illustrates how to get the file names. foreach (MultipartFileData file in provider.FileData) { Trace.WriteLine(file.Headers.ContentDisposition.FileName); Trace.WriteLine("Server file path: " + file.LocalFileName); } return Request.CreateResponse(HttpStatusCode.OK); } catch (System.Exception e) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); } } } 

Here where I found it is http://www.asp.net/web-api/overview/advanced/sending-html-form-data,-part-2
For a more thoughtful implementation
http://galratner.com/blogs/net/archive/2013/03/22/using-html-5-and-the-web-api-for-ajax-file-uploads-with-image-preview-and- a-progress-bar.aspx

+5
source

Publishing MultipartFormDataContent in C # is simple, but can be confusing for the first time. Here is the code that works for me when posting .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 publishing it, so I convert it to this object using JsonConvert.

+4
source

I debugged this problem:

 method.Add(streamContent, "filename"); 

This “Add” does not actually put the file in the BODY of multi-page content.

+1
source

All Articles