codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Upload/Download Files Using HttpClient in C#

How to implement file uploading/downloading on the server side and on the client side.

Changhui Xu
codeburst
Published in
4 min readDec 31, 2019

--

In this short blog post, we will take a look at how to send multipart MIME data to a Web API using HttpClient. We will create two applications to demonstrate the data transfer between the client side and the server side. The server side app is an ASP.NET Core web project, which includes a Web API controller for uploading and downloading files. The client side app is a Console project, which contains a Typed HttpClient to send HTTP requests for file uploading and/or downloading.

When an application needs to talk to another system, it is quite common that the application sends data to and receives data from the other system using HttpClient in the back-end. Based on this article in Microsoft Docs, it is straightforward to send HTTP requests and receive HTTP responses. However, most of tutorials and blog posts don’t talk much about sending FormData with a file object and a collection of key/value pairs using HttpClient. This blog post intends to provide the missing guide.

The complete source code is in my GitHub repository. Now, let’s review some code.

Web API for Uploading a File with FormData

This API action method follows the example in an article in Microsoft Docs. The implementation is lengthy, but the code logic demonstrates several checks to meet the security criteria. The following code snippet shows the example action method.

In the code above, lines 22 to 47 handle the File Disposition, and lines 48 to 65 handle the Form Disposition. When the MultipartReader reads sections in the HTTP request body, the request content is parsed and saved to physical disk (file) and memory (form data).

Web API for Downloading a File

This API action method finds the file and converts the file to an array of bytes, then returns a…

--

--

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Changhui Xu

Lead Application Developer. MBA. I write blogs about .NET, Angular, JavaScript/TypeScript, Docker, AWS, DDD, and many others.

Responses (4)

Write a response