I'm attempting to upload a file from my desktop application to a remote server. After browsing SO for a while this approach seems to be the cleanest way to go about it. The problem is neither parameter is received at the server side. What am I missing?
private void AddFile(FileInfo fileInfo, int folderId)
{
using (var handler = new HttpClientHandler() {CookieContainer = _cookies})
{
using (var client = new HttpClient(handler) {BaseAddress = new Uri(_host)})
{
var requestContent = new MultipartFormDataContent();
var fileContent = new StreamContent(fileInfo.Open(FileMode.Open));
var folderContent = new StringContent(folderId.ToString(CultureInfo.InvariantCulture));
requestContent.Add(fileContent, "file", "file");
requestContent.Add(folderContent, "folderId", "folderId");
client.PostAsync("/Company/AddFile", requestContent);
}
}
}
edit: This is the signature the server side is expecting:
[HttpPost]
public ActionResult AddFile(HttpPostedFileBase file, int folderId)
After a lot of trial and error, I got it. There were a few problems. 1) parameter names are expected in quotes 2) I was missing a bunch of header information. Here's the working code.
private void AddFile(FileInfo fileInfo, int folderId)
{
using (var handler = new HttpClientHandler() {CookieContainer = _cookies})
{
using (var client = new HttpClient(handler) {BaseAddress = new Uri(_host)})
{
var requestContent = new MultipartFormDataContent();
var fileContent = new StreamContent(fileInfo.OpenRead());
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
Name = "\"file\"",
FileName = "\"" + fileInfo.Name + "\""
};
fileContent.Headers.ContentType =
MediaTypeHeaderValue.Parse(MimeMapping.GetMimeMapping(fileInfo.Name));
var folderContent = new StringContent(folderId.ToString(CultureInfo.InvariantCulture));
requestContent.Add(fileContent);
requestContent.Add(folderContent, "\"folderId\"");
var result = client.PostAsync("Company/AddFile", requestContent).Result;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With