7.5: Adding PhotoService
Adding DTOs
Inside of the .Models/Photo folder, add a new class called PhotoForCreation.cs. This will represent the data we will send from our client to our backend.
The IFormFile property is used to hold a file sent via HTTP. Read more about it in the docs if you'd like..
We'll also set the DateAdded property in the constructor to set the creation date to whenever this is instantiated.
Next, In the same folder, add another new class called PhotoForReturn.cs. This will represent the data we will return after creation.
Adding IPhotoService and PhotoService
First, add a package reference to CloudinaryDotNet
in EFConnect.Services.csproj
:
Next, we'll add a IPhotoService to our .Contracts folder with two methods : AddPhotoForUser()
and SaveAll()
:
In the .Services folder, add a new class called PhotoService.cs
In the constructor, we'll inject our UserService and Cloudinary settings into the Controller.
We'll also initialize a new Account (from the CloudinaryDotNet namespace) and give it the values from our configuration.
We'll then initialize a new Cloudinary object and pass it our account. The Cloudinary object is what we'll use to access the methods to upload photos.
There is a lot going on in this constructor, and if you'd like to understand this better - you might consult the Cloudinary documentation - it's very thorough!
Now, we'll implement our AddPhotoForUser() method:
Whew! There's a lot going on here. We'll try to break it down into 6 steps.
Grabbing the user from the database
Creating a file variable holding the path information on the uploaded photo (our IFormFile property)
Creating an instance of ImageUploadResult - holds properties for the uploaded image
Setting the properties on our photoDto from the ImageUploadResult
Calling the Cloudinary Upload() method with our File as our parameters
Creating a new photo from our DTO
Checking if the user already has a photo set to main. If not we set the uploaded photo to their main photo
Saving our photo to the database
Returning a PhotoForReturn - constructed after saving the photo to the database so we know the ID.
Again, Cloudinary's docs are your best source if you would like to understand what's going on better.
One pretty awesome thing to point out is the part indicated with a *
above. When we upload an image to Cloudinary - we're telling it to crop it to 500px x 500px. Ok. That's a bit interesting. But, we're also using Cloudinary's algorithm to try to identify the face in a photo and crop it where the face is centered! That's pretty cool for one line of code we have to write.
Next, we'll add the SaveAll()
method (it will be the same as in the UserService
):
Registering PhotoService
Finally, we need to register our PhotoService
in the ConfigureServices()
method in our Startup.cs
file in our .API project:
Last updated