Today we will learn How to upload a file with .NET CORE Web API Web API. We will create a simple ASP core web API that accepts the model with an image file.
Recently, I’m working on an ASP CORE web API project, in which we need to receive the image using form data. Basically, my App app developer wants to upload the image from the React Native App.
That’s why we create a POST API that accepts both images using multipart.
If you are new to dot net core then don’t worry. after reading this article you can upload, edit and delete an image using dot net core WEB API. we will show you all step by step.
I have a user table in our database as you can see below image and we are using the entity framework for communicating with the database. we will upload a user profile if I delete a user, the user profile also should be deleted.
Image Uploading in Dot net core Web API
Step 1: Create an Asp core web API project.
Step 1:Create a Model class UserDataModel.cs
for posting data to the controller.
public class UserDataModel
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string About { get; set; }
[Required]
public IFormFile ProfileImage { get; set; }
}
Step:3 Write logic for accepting images from the post data and deleting a user profile
[Route("api/[controller]/[action]")]
[ApiController]
public class UserController : ControllerBase
{
private readonly DbContext _context;
private IHostingEnvironment _hostingEnvironment;
public UserController(DbContext context, IHostingEnvironment environment)
{
_context = context;
_hostingEnvironment = environment ?? throw new ArgumentNullException(nameof(environment));
}
// Post: api/User/UpdateUserData
[HttpPost]
public async Task<IActionResult> UpdateUserData([FromForm] UserDataModel userData)
{
Dictionary<string, string> resp = new Dictionary<string, string>();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
//getting user from the database
var userobj = await _context.TblUser.FindAsync(userData.Id);
if (userobj != null)
{
//Get the complete folder path for storing the profile image inside it.
var path = Path.Combine(_hostingEnvironment.WebRootPath, "images/");
//checking if "images" folder exist or not exist then create it
if ((!Directory.Exists(path)))
{
Directory.CreateDirectory(path);
}
//getting file name and combine with path and save it
string filename = userData.ProfileImage.FileName;
using (var fileStream = new FileStream(Path.Combine(path, filename), FileMode.Create))
{
await userData.ProfileImage.CopyToAsync(fileStream);
}
//save folder path
userobj.ProfilePicture = "images/" + filename;
userobj.UpdatedAt = DateTime.UtcNow;
await _context.SaveChangesAsync();
//return api with response
resp.Add("status ", "success");
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok(resp);
}
}
Lets do testing with postman
you can check the uploaded image in your wwwroot=>images folder, if you do not have a wwwroot folder then manually create the wwwroot folder in your asp core API project.
For deleting image file asp core when we delete user from the database , create a delete api , you can see in the below code.
// Post: api/User/Delete
[HttpDelete]
public async Task<IActionResult> Delete(int id)
{
Dictionary<string, string> resp = new Dictionary<string, string>();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
//getting user from the database
var userobj = await _context.TblUser.FindAsync(id);
if (userobj != null)
{
//Get the complete folder path for storing the profile image inside it.
var path = Path.Combine(_hostingEnvironment.WebRootPath, userobj.ProfilePicture);
//checking if "image" exist then delete it
if ((!Directory.Exists(path)))
{
System.IO.File.Delete(path);
}
_context.TblUser.Remove(userobj);
await _context.SaveChangesAsync();
//return api with response
resp.Add("status ", "deleted successfully");
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok(resp);
}
*Thank you so much if you have a question please comment
IFormFile
ASP.NET Core has introduced an IFormFile interface that represents transmitted files in an HTTP request.
ASP.NET Core has introduced IFormFile To upload files in ASP.NET Core. IFormFile provides us access to information of files for example FileName ,Header,ContentDisposition , ContentType, FileName etc.
This interface also allows us to read the contents of an uploaded file, and if you using asp core MVC with the view then the name of the IFormFile parameter and the name of the HTML FileUpload input element must be the same, otherwise, you will not get the file in the IFormFile.
The post [Simple Way]- Image Upload in .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#
- Simple Way Find and replace text in Word document using C#
- Implementing “Remember Me” Feature in ASP.NET MVC
- [Solved]-Cookie loses value when page is changed in MVC
- How to post File Upload and other form fields to one action Asp .Net MVC C#
- How To Post File and Data to API using HttpClient C#
- Create ASP.NET Core Web API Without Entity Framework
- .NET Core Web API Using Code First Entity Framework Approach
- Create Asp.Net Core Web Api Using Entity Framework Database First
- Registration form with image upload in MVC using jquery Ajax
- How to make an Inline editable table in MVC using jquery?
- CRUD operation using partial view in MVC with modal popup
- Insert Update Delete Using Jquery Ajax and Modal Popup in Mvc
- Crud Operations in MVC Without Entity Framework
- Create Login,Signout and Registration in Asp .Net Mvc Using Entity
- Export Gridview to Excel and Csv in Asp .Net With Formatting Using c#
- How to Display Binary Image in Gridview from Database in Asp .Net c#
- [Solved]-How to Upload pdf file using jquery MVC?
- [Solved]-Uploading both data and files in FormData using Ajax MVC
- C# -Saving a base64 string as an image into a folder on server in Web Api
- [Solved]-Download pdf file from link and save in local file folder in Asp .Net
- [Solved]-Delete Files older than X Months,Days,Minute in a Directory- C# .NET
- [Solved]-LEFT OUTER JOIN in LINQ With Where clause in C#
- INNER JOIN,RIGHT JOIN,LEFT JOIN USING LINQ IN Multiple Table C#
- [Solved]-Convert Base64 To Image And Save in folder and Display it- C#
- [Solved]-How to Overlay Two Images in .NET-C#
- How to Create Multilingual Website in Asp .Net
- C# – How to add double quotes to a string that is inside a variable
- Update an Image with Upload Button For Each Row in Gridview-Asp .Net
- How to Bind Data in DataList Control in Asp.Net – C#
- Upload and Display an Image in Gridview From Image Path in Database -C#