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#
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.
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.
I hope it clarifies your concern if you have any doubt please comment.
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.