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#
- Xamarin form - how to upload and retrieve image using sql server web api
- How to upload pictures in ASP.net Core Web API and Angular 13
- ASP NET Core Web API disable TLS 1.0 and TLS 1.1 support
- How do I implement data validation attributes on a list of derived types in Asp Net Core 3.1 Web API
- Loading Image from Asp.net core Web API 3.1 Folder outside of "wwwroot"
- Asp.Net Core HttpPost API for Upload Image results in Could not get any response
- web API 2 image upload with Object
- How to setup angular 7 to communicate with net core web api in VS 2017
- ASP.NET Web API upload image to SQL Server database
- Web Site call to asp.net web api - image upload unsuccessful
- Facebook JWT authentication using ASP.NET Core Web API
- Error on try to post file from Angular 6 to ASP.NET Core Web Api
- .net core Web API - 415 Unsupported Media Type
- ASP.Net Core 2.1 Web Api 2 And Active Directory Credentials
- Post generic class in .net core web API
- .net core web API access variable in controller from other classes
- ASP.Net Core 2 Web API performance metrics in database
- ASP.NET Core Web API multiple actions with the same action verb but different signature
- How to return XML from ASP.NET 4 Web API to ASP.NET Core 2 application?
- Correct way to pass object reference into .NET Core Web API
- ASP.NET Core 2.0 Web API throwing 500 error and not allowing access on http post
- Etsy API Image upload error: The request body is too large
- GetContent root Web API .NET Core xunit ClassFixture
- C# Core Web API controller optional Array default value
- How does ASP.NET Core Web API build URLs?
- upload image files using google drive Api
- prevent submission of contact form to .net core web api
- Running multiple ASP.net core web api applications on a single Kestrel server instance
- Cannot install EntityFramework 6.1.3 on my Web API .Net Core Project
- upload file from angular2 using web api 2 c#
- .NET Soap Client WSDL with no defined methods
- Why does DateTime's AddMonths function takes Int32 parameter and not Int16
- Is it possible to Update/Save new Record on databaseA on ServerA when databaseB on ServerB is updated?
- NLog Concurrent Requests into different files
- How to neglect automatically generated attributes and add new attributes in its place?
- Implicit Animation of Blur or Other Brush Effect
- Saving and retrieving .avi file from Oracle 11g using c#
- New line disappears after Invoke
- C# Raspberry pi Linux serial port permission denied even as root
- Create a hexagon made up of smaller hexagons. Unity, c#
- Passing values from button click event to jquery
- Model Binding a checkbox?
- while reading from a socket
- Update a program setup
- How can I find out if there are unsupported characters in a string?
- Programmatically Import Block Into AutoCAD (C#)
- The tag 'MultiResImageChooser' does not exist in XML namespace 'clr-namespace:MultiResSnippet'
- How to use html2canvas JavaScript with Selenium webdriver in C#
- Visual Studio - Add a button/checkbox to a toolbar to switch the readonly file property,
- Inserting FK values in Entity Framework that already exist (identical entries) in one table without updating the primary key of another table