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 to enrich azure b2c token with custom claims using api connectors and asp net core web api
- Secure Web API with Form Authentication (Authorize) and Basic Authentication (Message Handler) together
- asp net web api custom filter and http verb
- Grouping and Versioning not working well together in swagger in asp.net core 3.1 web api
- ASP .NET Core - sign in as other user / impersonate user and way back
- Returning Binary Data from ASP .Net Core MVC using Serverless and AWS API Gateway
- How to receive both File and data POSTed to an ASP.net core 2.1 Web-API endpoint
- C# Core 1.1 Web API Receive zip file
- How to extract filename and other properties from multipart form data prior to uploading file to azure
- C# Web Api - Upload and Read data from excel file without saving the file
- Reading and storing static look up data in ASP .Net Core web app
- Asp Net Core Web Api POST Request.Body always length 0
- Enabling ASP.NET Web Api to accommodate both JSON and Form encoded data
- Asp.net Core rc2 web api file upload
- Concurrent web api requests and how to handle state in ASP.NET core
- Enabling CORS in .net core Web api and angular 6
- Keeping state of logged in user in ASP .Net Core Web API
- ASP Web API and Autofac Integration Exception
- ASP NET Core Minimal API always returns 200 instead of specified 204
- how to use ssl certificates with gRPC and ASP Net Core 3.0?
- ASP .net Web Api downloading and viewing images
- Image Uploading in Dot net core Web API
- Accept x-www-form-urlencoded in Asp .net core Web Api
- How to Publish a Web API net core 3.0 in multiple servers
- Upload Large Files using Angular 8 and .Net Core Web API
- WebHost doesn't exist in the current context in Asp Net Core 2.2 default API template
- How to upload a file with other data in ASP.NET Core Boilerplate Application service?
- CamelCase not working in net core 6 web api
- Asp MVC and Web Api Async Controllers
- Disposed object error when dealing reading multipart form data in asp.net mv4 web api
- Determining the parent process id from C#
- How do I use an MVC Role permission in a View?
- Composite pattern of sealed class that has no interface
- Is there a way to convert a DateTimeOffset into minutes since midnight?
- add a onclientclick to gridview pager
- Chart control data series
- Async Pattern - waiting for an Event before returning some value from a method
- Only add items to a dropdown list once
- XNA close the game
- C# Case insensitive string comparison
- How do you name your query string variables? Short or long? Why?
- Why are static fields generally considered threadsafe?
- Get child window handles in C#
- WPF Tree View with Hierarchical data template and multi types
- What's a Good Twitter SDK for C#?
- C# DateTime.ParseExact with backslashes in format
- RichTextBox and UserPaint
- Directory.GetDirectories returns wrong results with a pattern of *.*
- Why does DateTime.ParseExact throw an exception with "dd.Mm.yyy" format and a date with a 4-digit year?
- Use .NET 4.0 or .NET 3.5?