Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload a file and a parameter to a remote server via HttpClient PostAsync method?

Tags:

c#

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)
like image 655
Billdr Avatar asked Jan 11 '23 19:01

Billdr


1 Answers

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;
            }
        }
like image 141
Billdr Avatar answered Feb 06 '23 13:02

Billdr