File Upload and Download with Spring Boot - REST API

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up everyone and welcome to daily code buffer in this video we are going to see how to upload and download a file using springboard so we are going to create a rest api that will allow us to upload a file and that particular file will save to database so we are going to use the mysql database for this particular example and we are going to save that particular file as a blog format in the mysql and we will also create an api to download that particular file when we hit that particular api so we are going to create two apis one to upload a file and one to download a file the same implementation you can use for all sorts of file and you can mix and match with the other data's as well ideally when you are uploading a file from the ui application you will be sending in a form data so we are going to collect that particular form data and we are going to process that file so without wasting any time let's go to the computer and let's create the application [Music] so yeah what i'll do i'll just open the intellij idea and here i'll create the project from the intellij idea you can create the same project using the spring initializer as well the same dependency you need to add so let me just create a new project from here here i'll be selecting spring initializer if you want you can go to the browser and go to start.spring.io and from here you can create the project let me go to the spring initializer over here and this is the project i want to create i'll just name as spring boot file upload okay simple but we'll be doing uploaded now on both and i have added the location as well my language is java type is mu1 i'll add the group as com.daily code buffer and my package name i'll just keep it as file mngt file management okay and my project sdk is java 11 click on next now we can add the dependencies i'll add the lumbar dependency i'll add the web dependency i'll add mysql dependency that is mysql driver and i will also add the gpa dependency so you can see that we have added four dependencies that is the lumbar for creating our boilerplate code the next is spring web to create the web application mysql driver to connect my spring application to the mysql database and spring data gpa to act as a middleware to connect our application to the database now let's click on finish and create the project now here you can see that the project is created let me just close the unnecessary windows now this is your project now let's add all the configurations the first configuration that we have to do is as we are going to upload and download the files we are going to work with the multi-part files so from this springboard application we need to enable that so let's go ahead and enable that for that we will go to the src main resources and we'll go to the application.properties and here we will add the properties to enable it so what i'll do i will just say spring.servlet.multipart.enabled equals to true so your multipart is enabled now with this we need to add some more configuration as well in our application to handle the size of a file so let's add that as well i'll just copy this detail and i will explain you okay so these are the fields you can see that it's spring dot sublet dot multipart dot file size threshold equals to 2 kb so this is a threshold after which the file will be start writing to the disk and the next is max file size that is spring dot sublet dot multipart max file size so maximum file size is 200 mb and maximum request size i have added as a 215 mb so these are the configurations for your multi-part file upload download how we are going to handle it now as we have also added spring data jp and mysql driver we need to add the configuration to connect our springboard application to the database as well so let's add the properties for that as well so this is the properties for that you can see that i've added spring.datasource.url jdbc mysql localhost 3306 this is where my my sequel server is running now let me just add the schemas file underscore db okay so this is our schema so this particular schema that we have to create and the other usual url stuff that is the use ssl equals to false server time zone equals to utc use legacy date time code equals to false all those stuffs i'll add this codes link of github in the description below so you can check this out you can directly copy this and the username and password for my database that is root and root i have added that and i have added the dialect as well and you need to make sure that if you are using mysql you add the dialect as mysql inno db dialect okay and spring data jpa hibernate ddl auto equals to update so whenever there is a modification in our entities it will get reflected in our database so that's the configuration let me just create this schema i'll go to the mysql workbench if you're not installed mysql or mysql workbench you can go ahead and install that if you just search with the mysql workbench in mysql server you will get the first link and you can download it it's very easy so i will just logged in to my server with my credentials and here i'll just create the create new schema and i'll give the schema name that is file db and hit on apply and my schema is created file db let me go back now let's build the application let's create all the different classes and packages so let me just go here i need to go to the java and here i need to create some of the packages so let me just create package controller i need package service to create the services i need package to create the entities for the model i think i need to rename it let me just refactor rename and this should be model okay model service entity controller and i need one package as repository okay now let's start creating the entities so first let me just create the entity i'll go here and i'll create the new java class that says attachment and for this attachment i'll just annotate with entity to make it as an entity and i'll annotate with other data for our data setters and i will annotate with at the rate no aux constructor as i need it and now let's add the fields so i'll just add private string id private string file name private string file type and private byte array of data okay so these are my fields now for my id i need to annotate with at the rate id for our primary key and then how this particular primary will be generated so for that at the rate generated value and here i'll define the generator generator equals to uuid and i'll create a generator so this would be generic generator it would be generic generator and here the name would be uuid and what would be the strategy this will be in the course okay and the strategy would be uuid too okay my id is done now if you come here for your data that is the byte array you need to store this data as a blob so i will annotate with it lob okay so all your data whatever the file that you're going to upload that will be stored as a byte array data in the blob okay so directly the entire file will be stored in your database and you want you can fetch the data as well from that directly now there is another approach as well where you will store the file in the directory and the path of the directory you will store in the database that is also the valid approach that is also the widely used approach now with the cloud in picture you can upload the file in the cloud as well and the link for that particular cloud wherever you wherever you have stored the file that link also you can save in the database that is also approach you can follow so that's what we have done here we will be saving in the database for now i'll create one constructor which will take all these three fields one two and three without id okay so you can see that my and it is ready now based on this entity i can create the repository so let me just go ahead and create the repository in the repository package i will generate the new class and i'll say attachment repository and this will be the interface and this extends gpa repository and its of type attachment and the ids of type string and i'll annotate with anthra repository cool right your repository is ready your entity is ready now let's create a model with which you will be sending the data and receiving the data so let me just create a model that says response data and i'll annotate with the rate data at the rate nuage constructor at the rate all lux constructor and here i'll add fields i'll just define private string file name private string download url download url private string file type and private long file size cool right so you can see that your model is also ready now what you have to do is your controller service and repository is also already created so your controller and service so let me just create the service interface and service class so i'll go to the service and here i'll just define new class that will be the interface so i'll just define attachment service let me just define the implementation for this service as well attachment service impl and this will implements attachment service and this is your service so we'll annotate with service cool right so your service and your service interface both are created now let's go ahead and create the controller so i'll go to the controller package and let's create the controller java class attachment controller and i'll annotate this with other trust controller to make it as a rest api controller cool you can see that my all the classes are created now in my controller what i need is i need the object of the service so let me just create the reference for that private attachment service and i'll just create the constructor okay and here i need to create a method which uploads the file and then download the file so let's do that i'll just create one method and i'll just say public which will return response data which we created and i'll just name as upload file and this will be boost mapping with slash upload as the url and here what i will be taking is i'll be taking the request parameter from the form okay so what do the request param request param would be file and this would be the multi-part file and i'll just give the name as a file okay so i am injecting multipart file which i am uploading from the form i'm submitting from the form to my method okay now this particular file whatever i'm getting that i need to convert it to byte array and i can directly save to the database now here what i'll do i'll just say attachment attachment equals to null i'm just defining here and let me just do attachment equals to attachment service dot save attachment i'm creating one method and i'm passing file okay this method is still not created so we need to create this method so let me just go ahead and create this create method save attachment in attachment service let's do that you can see that the method is created now i need to implement this method so let me go here let me go to the attachment service mpl and let's implement this method now in the attachment service impl here i will be doing the code to save the file to the database so here i'll need the reference of the repository so let me just create that i'll create private attachment repository and object for that attachment repository and this will again need the constructor to bind in okay so this is a constructor and this is injected and it's assigned back cool right now let's implement this method i have got the file here now what i'll do i'll just get the file name from here so i'll just define string file name equals to string details dot clean path and i'll just get the clean path from file dot get original file name let me just add the try catch block and i'll get the exception here here what i'll do if here you can do all sort of validation like what is the size and the file name is correct or not all the type of exceptions or all the type of validations that you can handle and if there is any exception you can throw the exception and you can handle the exception you can pass on the proper exception message error message to the client so here what i am checking is file name that contains any invalid character if so throw new exception that says file name contains invalid path sequence okay after if i just create the object of attachment equals to new attachment and within this i'll pass file name then i'll pass file.get content type and then i'll pass file dot get data sorry get bytes okay once you get the attachment we'll do return attachment repository dot save attachment simple right and here if there is any error exception you can throw back the exception throw new exception could not save file add exception to method signature yes okay so here is also added and it's also added in the service and we can handle the same in the controller okay here we can do try catch as well and handle it and now here what we can do is you can see at this particular point your attachment is saved in the database okay now this attachment from this particular attachment object what you can do is you can directly send it or you can create the response data now what we have added in the response data is file name download url file type and file size so all this information we can get directly but to create a download url we need to do some code and when you click on the download url that particular file which is already saved in the database that needs to get downloaded so we need to build this url and whatever the url that we are going to build the same we need to create a method to download it as well okay so let's do that so let me just create download url equals to blank now what i need i need download url equals to i need to get the current context path okay so whatever my application is running that i need so i can get that from the servlet uri components builder dot from current context path from here we will get the current context path and then from here i can add path that after the path whatever it is that is localhost 8080 slash whatever then i if i add the another path that is the download then dot path if i add attachment dot get id whatever the id it is and then dot to uri string cool so this is the entire url we created that is the your current context path slash download slash the id that you want for a particular okay which particular id you want to download so that's what we have created the download url now let's create the object of it and let's send it so here we will just create return new response data and in this response data what i need i need attachment dot get file name then i need download url then i need file.get content type then i need file.getsize cool right your response data is created so we will get a entire object which will contain the file name what was the file name what was the url to download that particular file the content type and the size as well now whatever the url that we have created here for that we need to create the api to download as well so let's go ahead and do that also so here what i'll do i'll create one more method that says public response entity this is the return type and the written type would be of resource and this resource would be from the arc dot spring framework dot core dot io okay and i'll just say download file and and this will be get mapping okay and it will be slash download slash file id so that's the path variable that we are going to pass so we need to inject the path variable as well so i'm just injecting path variable and string file id cool right it's simple now here we need to build it so what we will do here i'll just say this is the attachment equals to null and we need the entire attachment so i'll just say attachment equals to attachment service dot get attachment and here in the gut attachment i'll just pass the file id or you can say attachment id okay now let's create this method this method is not available so let's create this method in the attachment service okay now we need to implement this method as well so let's go to the attachment service impl and let's implement the method implement methods okay now this is the method now this get attachment is very simple what we will do we'll just do one return attachment service sorry attachment repository dot find by id find by id based on the file id dot or else throw will throw new exception file not found with id file id and i'll just add add exception to the method signature yes hope so you are able to see this you can see this is a simple method get attachment where we are getting the file id and from the attachment repository we are doing find by id with the particular id that we got because that's the primary key and if we didn't get the primary key then we are doing or else throw the exception file not found now let's go back to the controller and here also you can see now we're getting the error so we need to add an exception to the method signature that's fine and you can do add the try catch block as well now once you get the attachment object what you can do you need to create the response and entity and we need to add some header information so browser can know what to do with this particular request so we'll just define return response entity dot ok dot content type okay what is the content type content time is media type dot parse media type okay let me just media type dot parse media type and i'll just do attachments dot get file type okay dot we need to add the headers so in the header i'll define http header http header dot content disposition and here i'll just define attachment and file name equals to double quotes plus attachment dot get file name plus backslash okay dot body now as we need to pass sit in a resource and my data is in the byte array so i'll just define byte array resource what is the resource attachment dot get data cool right this makes sense you can see that simple what we did in the response entity what we are doing is we are just defining the content type and the header information content type is whatever the content type of the file itself and the header information we defined as a content disposition so whatever the content is those content will be disposed it will be downloaded and what it would be it would be the file name whatever the file name we have added that particular file name will be downloaded as as that particular file limit will be downloaded and we returned as a byte array resource and the data would be whatever the attachment dot get data now what we will do we will just start our application and we will see this so let me just start the server i'll just enable the annotation processor okay now you can see that my server is started now we will go ahead and check the database we'll just refresh all we'll go to our database that is the file db and you can see that our table is created and there is no data okay let's go back and for this let's open the postman to test this api okay this postman let me just open the new request and this will be the post request and here i'll just define http localhost colon808 slash upload and this will be the post request and we need to go to the body and this will be the form data and here key would be file and here you need to change to file because we are uploading a file so let's attach the file and what i'll do i'll just go to the pictures and let me just upload this one okay and when i hit on send you can see that i got the request back that is the file size what was the file type what was the download url and what was the file name all the things now if we go to the database and if you hit the query again you can see that the record is there and you can see the data this is in the blob format okay now if you get this url okay and if you go to the browser and if you hit this url you can see that your file is downloaded and if you open this this is the file that we have uploaded you can see that we just uploaded the file with saved the database and that particular file was downloaded with the download url as well now you can do the same thing with the multiple file as well the only thing is you need to look through the file and when you take the input here instead of taking just the multipart file you need to take the area of multipart file that's it that will be for your multiple files now the other thing you can do is if you want this entire byte format data which is saved in the database into b64 then you can convert this entire byte array to base64 and you can pass the data back as well so that's what i wanted to share everyone was asking about this tutorial how to upload the file and download the file from the springboard with the help of the rest apis so this is what you will do and when you are creating the form in any of the ui application you will directly submit the form itself and you will pass the data as the form data okay you will be passing the data as the request parameter not the body so if you have doubts regarding any of the things that we have covered then do let me know in the comment section below if you like this tutorial give us a thumbs up and subscribe to my channel for the upcoming videos you can also join this channel by clicking the join button below and you can support the channel as well so that's been it i will see you in the next video till then happy coding bye [Music]
Info
Channel: Daily Code Buffer
Views: 39,954
Rating: undefined out of 5
Keywords: spring boot, java, spring boot file upload, file upload to database, spring mvc, file upload spring boot rest api, file upload and download in spring boot, file upload and download in springboot mysql db, image upload with spring boot, file upload with spring boot, file upload, file upload using spring boot, spring boot file upload and download
Id: dqm9Ciy-cjc
Channel Id: undefined
Length: 29min 4sec (1744 seconds)
Published: Sat Mar 19 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.