How To Post File and Data to API using HttpClient C#

In this post, we are going to learn how to send a file through the HTTP client in asp .net c#. The idea is that you can send a file. As we know the HTTP client will work for whatever kind of file.

For example, you can send an Xls, a PDF, a word document, or whatever you want to send through the HTTP client class to a web API. So let me show you first what I have in my Asp core REST web API to receive the file before we code up the solution to send the file through the HTTP client.

In this post, we will cover the following points

  • How to post file and data to api using httpclient c#
  • HttpClient multipart/form-data upload
  • How to send a file and form data with HttpClient in C#
  • Upload Files with HttpClient to ASP.NET WebApi or Asp Core
  • Multipart form-data in HttpClient Post REST API

So here we have a file rest Web API endpoint, which is an API that I designed specifically for this example. Here I have a post endpoint and as you can see, it accepts UserProfileModel model class as a parameter, and UserProfileModel has properties UserId, Name, Address, Description, and Image which is a representation of a file. And the name of this parameter is file.

And also we are using FromForm because in order to receive files I need to use FromForm I cannot use Frombody.

Now here what I’m doing is that I am using this service, which allows me to save the file into the webserver specifically in the www root directory.

REST API upload file example C#

[HttpPost]
        [Consumes("multipart/form-data")]
        public async Task<IActionResult> Profileupdate([FromForm] UserProfileModel userProfileModel)
        {
            ApiResponse resp = new ApiResponse();
            resp.code = 100;
            if (!ModelState.IsValid)
            {
                resp.msg = Message.invalid_model;
                return Ok(resp);
            }
            try
            {
                var file = userProfileModel.Image;
                string file_Extension = Path.GetExtension(file.FileName);
                string filename = Guid.NewGuid() + "" + (!string.IsNullOrEmpty(file_Extension) ? file_Extension : ".jpg");
                var uploadspath = Path.Combine(_hostingEnvironment.WebRootPath, "profilepicture") + "/" + userProfileModel.UserId + "/";
                // Get the complete folder path and store the file inside it.  
                using (var fileStream = new FileStream(Path.Combine(uploadspath, filename), FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);
                }
                resp.code = 0;
            }
            catch (Exception ex)
            {

            }
            return Ok(resp);
        }
		
		
 public class UserProfileModel
    {
        public int UserId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Description { get; set; }
        public IFormFile Image { get; set; }
    }	

HTML for updating the user profile

Now let’s go to our Html page, which is our web application, and from here that we want to send a file with user data information.

<form>
    <fieldset>
        <legend>Post file and data to api using httpclient</legend>
        <div class="form-group">
            <label for="txtName">Name</label>
            <input type="text" name="txtName" class="form-control" id="txtName" placeholder="Name" />
        </div>
        <div class="form-group">
            <label for="txtAddress">Address</label>
            <input type="text" name="Address" class="form-control" id="txtAddress" name="txtAddress" placeholder="Address" />
        </div>  
        <div class="form-group">
            <label for="txtDescription">Description</label>
            <input type="text"  name="txtDescription" class="form-control" id="txtDescription" placeholder="Description" />
        </div>  
        <div class="form-group">
            <label for="fileupload">Profile Picture</label>
            <input type="file" class="form-control" id="fileupload" />
        </div>
        <div class="form-group">
            <input type="button" id="btnregistered" value="Update" />
        </div>
    </fieldset>
</form>
How To Post File and Data to API using HttpClient C#

Send a image file and form data with HttpClient

and Onclick submit button we are calling this action method. using below code you can Post file as well as some parameter to web api.

 public ActionResult UploadImages(FormCollection collection)
        {
            ApiResponse response = new ApiResponse();
            HttpFileCollectionBase files = Request.Files;
            byte[] data;
            string Name = collection["txtName"];
            string Address = collection["txtAddress"];
            string Description = collection["txtDescription"];
            if (string.IsNullOrEmpty(Name))
            {
                response.msg = "Please enter Title..";
                return View(response);
            }
            if (string.IsNullOrEmpty(Address))
            {
                response.msg = "Please enter Address..";
                return View(response);
            }
            MultipartFormDataContent multiForm = new MultipartFormDataContent();
            multiForm.Add(new StringContent(Name), "Name");
            multiForm.Add(new StringContent(Address), "Address");
            multiForm.Add(new StringContent(Description), "Description");
            multiForm.Add(new StringContent("343"), "UserId");
            if (files.Count > 0)
            {
                //adding list of images in the MultipartFormDataContent with same key
                for (int i = 0; i < files.Count; i++)
                {
                    HttpPostedFileBase file = files[i];
                    if (file.ContentLength > 0)
                    {
                        ByteArrayContent bytes;
                        using (var br = new BinaryReader(file.InputStream))
                        {
                            data = br.ReadBytes((int)file.InputStream.Length);
                        }
                        bytes = new ByteArrayContent(data);
                        multiForm.Add(bytes, "Images", "filename.jpg");
                    }
                }
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri("http://localhost:44246/");
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage httpResponseMessage = client.PostAsync("/api/Profileupdate/Uploadimages", multiForm).Result;
                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    //string ss = httpResponseMessage.StatusCode.ToString();
                    response = httpResponseMessage.Content.ReadAsAsync<ApiResponse>().Result;
                }
                else
                {
                    var content = httpResponseMessage.Content.ReadAsStringAsync().Result;
                    response.msg = content;
                    //string str = await httpResponseMessage.Content.ReadAsStringAsync(); ;
                }
                return View();
            }
            else
            {
                return View();
            }

        }

I hope it clarifies your concern if you have any doubt please comment.

Thank you..

 

Because this file that we have here must match this file that we have here. It is the name of the parameter now. Com. And here we want to put the file name. Now I will say wait step client do post sync and I want to pass URL CMA request content and that’s actually

With this, we’re good to go. Let me first make sure that in www. Root, there is nothing right. So now let me press control five to run our application, both the console application and also the API. As you can see the end, means that we finish.

So let’s go back here and let’s see what we have. Let’s go to the Solution Explorer. In the www. Directory, we have a file folder. And in here we have these text file that has a Git as its name.

That is because I don’t like to leave the same name on the file because, in the future, we could have collisions in the name of the file. But if I double click here, you are going to see that we have this is an example which is the same content that our example TXT file has. Therefore, as you can see, we were able to send a file from a client to our API by using the HTTP client class.

Ashok Patel

I'm a software engineer, having good experience in software programming web designing with great command on ASP.NET, React JS, Angular JS,.NET Core HTML5, JavaScript, T-SQL, JQuery.
Also have great experience in Electronics and electrical engineers design.
I like to do RND and Research.

Add comment

Your Header Sidebar area is currently empty. Hurry up and add some widgets.