Today we will learn how to Receive files and other form data together in ASP.NET Core Web API.
We will create a simple ASP core web API that accepts the model and image file both.
Recently, I’m working on an ASP CORE web API project, in which we need to receive the multi-part form data within a user model. Basically, my app developer wants to update the user profile that screen also has a user profile picture. That’s why we need to create a POST API that accepts both images and JSON at the same time in a single POST using multipart.
So the first question which comes to my mind is Is it possible to POST JSON and the image at the same time in a single POST request? and How to do Multipart-form-data file upload in asp.net core web API?
How can we upload image with other parameter in core API ?
so let’s create a Multipart/form-data images upload with JSON asp.net core API.
Step 1: Create an Asp core web API project in .Net 6 and add an API controller.
Step 1:Create a Model class for posting JSON data.
UserProfileModel.cs contains the four properties UserId, Name, Email_Id, and Image.
public class UserProfileModel
{
[Required]
public int UserId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Email_Id { get; set; }
[Required]
public IFormFile Image { get; set; }
}
Step:3 Create POST API that accepts both images and JSON
Now in the controller, I have created a post API that accepts the “UserProfileModel.cs” model as a parameter.
[Route("api/[controller]/[action]")]
[ApiController]
public class UserProfileController : ControllerBase
{
private readonly AdequateDbContext _context;
private IHostingEnvironment _hostingEnvironment;
public UserProfileController(AdequateDbContext context, IHostingEnvironment environment)
{
_context = context;
_hostingEnvironment = environment ?? throw new ArgumentNullException(nameof(environment));
}
// Post: api/UserProfile/UpdateUserProfile
[HttpPost]
public async Task<IActionResult> UpdateUserProfile([FromForm] UserProfileModel userProfileModel)
{
Dictionary<string, string> resp = new Dictionary<string, string>();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
//getting user from the database
var user = await _context.Users.FindAsync(userProfileModel.UserId);
if (user != null)
{
//Get the complete folder path for storing the file inside it.
var path = Path.Combine(_hostingEnvironment.WebRootPath, "images/");
//checking if folder not exist then create it
if ((!Directory.Exists(path)))
{
Directory.CreateDirectory(path);
}
//getting file name and combine with path and save it
string filename = userProfileModel.Image.FileName;
using (var fileStream = new FileStream(Path.Combine(path, filename), FileMode.Create))
{
await userProfileModel.Image.CopyToAsync(fileStream);
}
user.ProfilePicture = "/images/"+ filename;
user.UpdatedAt = DateTime.UtcNow;
await _context.SaveChangesAsync();
//adding image url dictionery for returning in response
resp.Add("imageurl ", user.ProfilePicture);
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok(resp);
}
}
In the controller constructor, I’m Injecting IHostingEnvironment and entity framework context class. using IHostingEnvironment we access the folder path in the Asp core.
private readonly DbContext _context;
private IHostingEnvironment _hostingEnvironment;
public UserProfileController(DbContext context, IHostingEnvironment environment)
{
_context = context;
_hostingEnvironment = environment ?? throw new ArgumentNullException(nameof(environment));
}
Now let’s perform testing the postman
let’s put debugger and see we are getting the files or not.
as you can in the above image ,we are getting the posted image file.
*Thank you so much if you have a question please comment
HTML multipart/form-data
HTML Forms are used to get information from users. This information may include feedback, personal information, messages, complaints, or other suggestions.
You will find HTML Forms on many Websites. You can see these as Sign Up Forms, Log in Forms, Payment Details Forms, Survey Forms, etc. Do you know that Google’s Search Box is also an HTML Form?.
In the forms, the necessary information is filled by the users. And this information is sent to the server. From where webmasters can access it.
Information about all Form Elements
HTML Forms are defined by Form Element. Form in HTML page works like a container tag. Within which Forms are created by defining other Form Elements. Apart from the Form Element, there are also many other important Form Elements. Which are being told below.
Input – Input Element is the second Required Element of HTML Form. Various types of Data Fields are defined in the Form by Input Element. Whose type Attribute determines.
Select – A drop-down list is defined in the form of the Select Element. More information than this is contained in one field itself.
textarea – By the way, Text Fields can be defined by Input Element. But, Multiline Data Fields can be defined only by the textarea element. Because only single-line data fields can be created from the input element.
When your application makes a POST request, we have to encode the data that are input informs that form the body of the request in some way.
HTML forms provide three methods of encoding.
- application/x-www-form-urlencoded (this is default)
- multipart/form-data
- text/plain
- Avoid to user use text/plain if you are writing client-side code ,use multipart/form-data when your form contains form input file type that means you are trying to upload the file in HTML oage i.e elements.
- if your form does not contain the file type input then you can use multipart/form-data , application/x-www-form-urlencoded.
The post [Easy Way]-Receive File and other form data together in ASP.NET Core Web API appeared first on Software Development | Programming Tutorials.
Read More Articles
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- How can i post both file and text data to web api using asp net core http client?
- ASP .NET Core Web API - Getting and extracting a .zip file from upload controller, using IFormFile
- Add custom attribute to OpenAPI specification file and swagger in .net core web api
- Bootstrap5 and other custom CSS not loaded in .net core web api
- How to handle encrypt and decrypt file in ASP.NET core web API
- Import excel file in Angular and pass data into ASP.NET Core API project
- POST Image and Body Data at the same time in ASP.NET Core WEB API
- Fetch and sort data from DB in ASP.NET Core Web Api
- Fetch and sort data from DB in ASP.NET Core Web Api
- Force ASP Core to display Model properties and not Form Data
- easy and robust way to version WEB API in the url?
- Pass json data as parameter using angular js and receive that in Web API method
- I need my code to Add and bind data to the gridview in asp web form
- Unable to receive form data in web api c#
- FormData in asp .net mvc with file upload and other data than files
- Proper way to de-serialize a property of type collection of abstract object in Asp.net Core web API
- How to do one to many relation with mongodb in Asp .net core web api
- ASP.NET Core Web API - How get all employees user details and roles in Entity Framework result
- .net core web app JQuery AJAX Front end not getting data from Backend .net core api
- How to check if a user re-logged in and accessing the same API in ASP.NET Core Web API
- IIntercept and read data before reaching the dotnet core ASP controllers
- I am trying to submit an object that contains some data and a file from the client app to the API app using ASP.CORE 5
- How to make all model properites nullable in asp net core api
- how to configure JWT authentication and Microsoft Authentication in asp.net core Web API startup class
- Asp.net Core Web API use Dapper to Execute Postgres function raise "Timeout during reading" and "Exception while reading from stream"
- ASP.NET Core Web API - implement multiple databases using Sybase and SQL Server
- Angular and ASP .Net Web Api on Plesk
- How to write Html in asp.net core web api , Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
- ASP.NET Core Web App and windows form app give different results on service references
- ASP.NET Core Web API - How to post JSON Serialized data into the database
- how to convert datetime to date in DataView.RowFilter in c#?
- How do I get the id from a XAML ListView when more than one table is used?
- regex for capturing digits and digit ranges
- Set the value of one property to the value of property containing a primary key
- iTween MoveTo and set a new parent at the same time
- how to change to string color name from System.Windows.SystemColors.WindowTextBrushKey?
- How could I make textbox 1 change the font size of the text in textbox 2. similar to changing font size in google docs or Microsoft word
- Named Pipe C# Server + Python Client
- Problems prompting for input from an SSIS package
- Merging several word Docs dynamically
- Cannot Bind Grouping property in ListView
- Make asp:HyperLink the list items in an asp:DataList
- How to instantiate a linkedlistNode of a generic type in c#
- Group Dates By Weeks Of Quarter
- C# -Connect unc path with credentials
- Assign a class to a this keyword
- suppress DataError Event in DatagridView
- How to perform fine grained access control in an asp.net MVC application.
- Code-First Migrations and DataDirectory for LocalDb
- How to keep object property "Required" conditionally, depending on object's use?