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());
This has been asked a number of times on SO. Here's some possible solutions:
C# HttpClient 4.5 multipart/form-data upload: C# HttpClient 4.5 multipart/form-data upload
HttpClient Multipart Form Post in C#: HttpClient Multipart Form Post in C#
On a personal note, check the post data being sent in the request, and check the response. Fiddler is excellent for this.
I know this is an old post But to those searching for a solution, to provide a more direct answer, here's what I've found:
Here's where I found it http://www.asp.net/web-api/overview/advanced/sending-html-form-data,-part-2
For a more Elaborate 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
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.
In my case I need to do something with the object after it posts so I convert it to that object with JsonConvert.
I debugged this the problem is here:
This 'Add' doesn't actually put the file in the BODY of Multipart Content.