DOWNLOAD FILES AS ZIP ARCHIVE FILE USING LARAVEL AND AXIOS
Sometimes, we need to download our files in a format of zip archive to download it once in response and view it just in one directory afterwards. Its more convenient and more professional to look when we apply it to our projects.
Hi there! In this toturial, I'm gonna teach you how to convert your files into zip archive and download it through axios request.
On this day, you will learn step by step how we can do it within less code and no packages both npm and composer to be installed.
LET'S START !
Step 1: Create Route
We have to create our route which will be called from our axios request as api endpoint
Step 2: Create Our Controller
Next, we have to create our controller named 'ZipController' as what we have stated in our route above. Inside this controller, we will create a method named download, this method will hold all of our codes to download files as zip archive.
This is your controller looks like
Don't worry if its messy, I will explain it later every block of the codes to understand whats happening inside of that download function.
Now let's continue, we will create our axios request.
That's it ! try to trigger that axios request and just make sure you followed all steps stated above, let's see the result :)
Now, lets go back to the controller topic stated above and explain every block of codes written there. Let's start
Make sure you have a folder named zippannels inside of your storage/app directory. Inside of this folder, put some files any type you want.
We will put a prefix of time to our zip name just to make sure our that it is unique inside of that directory
Now, lets initialize a variable called $zip_file_name with a value of the current path of the zip archive name we created above. We will use it later when we do further.
We will declare now the ZipArchive class which will do the zip archive convertion. This PHP extension enables you to transparently read or write ZIP compressed archives and the files inside them.
Okay, I know this block of codes makes you confused a little. On this part, we are already using the PHP class ZipArchive, if its successfully open the directory of our zip folder (which we will put on our files) then we will open the directory which holds all our files. We will loop it and add it one by one into our zip archive folder. After that, we will close our ZipArchive class just to make sure it will not arise any issue.
On this part, we are just making sure that the zip file was successfully created, if its successfull then we will download it directly.
As what you observe, we have a deleteFileAfterSend function at the last line. It means, after we download the zip archive file we delete it just to make our storage/app directory not populated.
That's all ! I hope you've learned today. Have a great day!