In this tutorial, you will learn how to
use jQuery to upload files to your hosting. Hey what's up, guys?
Senaid here from codingpassiveincome.com. The place where I help others to become a
web developer, much easier and faster than they will do it on they own. If that's
something that interests you consider subscribing. So, now I'm here at my
PHPstorm, I have started a new project. The name is jQuery file upload script.
I have created images folder and inside image folder I have one file logo.png.
I have also one folder uploads and an empty index.php file. First thing
that I'm going to do I will just create a normal HTML document, just a basic
design for this tutorial. So, inside body I'm going to have one
div, I will say ID dropZone, which is basically the place where I will enable
files drag and drop and also will be able to select files for upload. Inside a will say <h1> Drag & Drop Files... And here I will say, I will have one input
type will be file. Let's say I will set ID to the file upload. I
will give it name attachments and I'm going to say it is possible to select
multiple files. Above of this part I will put one image. It is just my logo, two new
lines and down below I will have h1 Let's say ID will be progress and
below that I will have also one ID, where later we will append files that the person
is uploaded, so it will be just like a preview. And pretty much that's it. I will
just declare, let's just quickly see, how does it go look. So, this is the basic design and I will just
add some styles. So, that it looks a little bit nicer.
So let's say for the body, I will say or better, let's use like this. And here
I will say for the dropZone. As you can see I'm using #dropZone, because
you are using here ID, if it was class use .dropZone and let's say border
I will say three pixel - and the color is basically my brand color. I can set the
padding to 50 pixels and let's say width I will say 500 pixels. So let's just see.
So as you can see it is in the center, or maybe I should just go. I will just use
just make it more simple, I will just say center, even if this is depression tag,
but for this tutorial, it is not that much important. So let's say like this and
for the files, I will say border 1 pixel dotted and I will use the same, I will padding 20 pixels
width 200 pixels and pretty much that's it. So, this is the basic design, I also
going the move this, okay. Okay, for the dropZone I can also see margin - top 20 pixels. So this is our basic design. For now I
will just set files display none. Okay, so, now the next thing that we need to do
once you have some basic design. We are going to include jQuery library and also
jQuery file upload plugin. So, first thing I will go to the code .jQuery.com
and here we have a list of all of the versions for the jQuery library. I will choose the latest one, go to the minifed, and here I will just copy this code. You
can also click this button here to copy to the clipboard, whatever you like to do.
And just before the closing body tag I will paste this code in and this is how I
love to use it. Okay and now let's just the download jQuery. You can just go to the
google and type in jQuery file upload plugin and after that, we can go to the
clone or download and hit download. I will just save it to the folder of this tutorial.
Save, okay. Go to the shown in folder, I'm going to extract here. And now you can
see here that we have a lot of the files, but the only folder with the files that we need is this one, JS . So, we can just move it here and other to delete.
Since I have set up some protections, I'm on a Linux, I will just quickly allow this files to be executed. Okay, and that's it.
So now if you are not on a Linux you don't need to do what I just did in the
terminal. And here I will just say script, source and I'm going to search in the JS
folder, vendor and here we have just one a file. We will include it. I will say type="text/javascript" and that's it. So, I will duplicate this line and just change the source. I will say iframe - transport.js and we need one more file. It is
jQuery.fileupload.js. And now we have everything that we need for this
tutorial. So we are going to write the code. So, I will say script type="text/javascript" and now I will just write document ready function. Okay and inside
of this function so once the old libraries are loaded and the complete
document is loaded, this function will execute. So I will say here, I will make a
reference the files. I will say files. The next time when we use it it
will be extremely fast and here I'm just going to set up some events for
this file upload. I will say #"fileupload".fileupload becouse that is the name of our plugin. And inside here I'm going to write some basic options. So I will say like this, and we will say URL which is where we are going to upload our file. It will be index.php. After
that I will say dropZone which is where I want to enable dropZone. So as you can see I have already one div with ID. So, I will say here dropZone: "#dropZone". If it was a
class here I will say .dropZone. Okay, after that I will say dataType,
which is what type will be returned from the server in the PHP I will use the
JSON, you can use text or any you want, but I love to use the JSON. And here I am going
to say autoupload.false, because I want to verified the files before the files
are uploaded. And now I'm going to set up some events, so I will say .on, and here I
will say "fileuploadadd". So, when some file is added, this function here will execute. And I will set up those parameters, also I'm going to add
another even. I will say "fileuploaddone", which means what happen once the file has been
uploaded. So, I will say function (e, data) same parameters and this. And last thing is last event is "fileuploadprogressall", which means I'm using the one progress for
all files. Function, and that's it. So now we have set up
three events when someone add file, when the files uploaded and in the process of uploading
files we will just display some informations in the percentages. So, let's
say, what will happened once the person just add the file. So, we are just going to set
up, since in this tutorial I will just make an upload of image, I will just
verify it is an image file. So, I will say var fileTypeAllowed and let's say here I
will just use a regex. So, I will say here / so, I will allow any caracters and after that it will go with . and I will allow gif|jpeg|png, okay. So it needs to finish with those, through all. So, here now I'm going to say
if (!fileTypeAllowed.test). Let's say if not. Now I need the name of the file. So let's just quickly show you how to get that. So in this data we have some informations. So, let's just check those informations. Okay here, let's try. I want you to completely understand this tutorial. I will just choose
files, let's hit those are some test file. So let's say I will use this one.
And now here in the console you can see some informations this is an object file
and inside this object we have a lot of different information, but what we are looking for is original file. And as you can see
here I have some basic informations like last modified, last modified date, the
name of the file, size, type of the file, etc. What we are looking for is the
name and the size. We are just going to take those two things. So, how you are
going to access, we will say data.originalFiles. And now it is the first
one and we are going to access the name. So I will say console data.originalFiles 0 and here I will say name. Let's see what will happen.
Refresh, choose files let's use this one and as you can see the name is myPicture.png. If I choose any other, it will get that. and so on. So this is very
important. So, if I select all files, you can see what will happen. Okay, so now we can say var fileName =
and for the size you can just say here fileSize. Ok and now let's make a test. So if ((|fileTypeAllowed.test (fileName)). Let's say we have here error and let's say for the error we will set color: red. Okay, here inside
this error, I will say error.html Only image images are allowed. It's really
not important. So, let's test now. Choose files, let me use this one. Only image are allowed and if we now choose some picture there won't be any
message, which is great. Now the next thing thing that we want to check is the size. So let's say else if fileSize > 500 KB, like this. So it's bigger, sorry. We will say ("error").html('Your file is too big! Max allowed size is :500KB') Okay, let's try it. choose files. So now if we use this one, we can see that it's
picture, but when we try to upload, it says "Your files too big! Max allowed size is 500 KB." And if we try any smaller, like this one. Hit open, sorry we need to refresh. Okay, like this one. It will work, which is greate. And if we try any other file, there is a problem. So this is just great functionality so far. And
let's say else. So, if the person is uploading image and if that image is not bigger than 500KB, we will just allowed the person to upload files.
So, I will say else ("error"), let's say there won't be any error, which is great. And here I will say data.submit which means start uploading this file, because we have checked and everything looking good.
Okay, so the next thing that I want to do is let's say, we are going to create this
file upload done. Okay, but in order to created we will need to write a code that is on our server, which is PHP code. So before that, let me
just finish this progress all. So I will say here let just check again the data what
we have here, so console.log(data). Just make sure you understand, F12, choose files, let's use this one. And as you can see now we have informations, loaded: zero, total.. Sorry, some problem like this. Okay, you have loaded, you have total
and you have bitrate. So, now if we want to calculate the percentage, we can get
directly from the data.loaded and data.total. What I'm going to do, I
will say here var progress = and have use function partInt, just to get an
integer value and here I will say data.loaded / data.total * 100, because we want to get percentage and just this. And I will
just say progress.html completed I will say here + progress + percent. So let's make a test. Choose files, I will use this one, it is
complete 100%, because this file is really small and for that reason
it seems that we just got this, but basically it is uploading. We can test
that, just by doing this, so I will do this just to show you. So now we want check anything, we will just allowed any fileType and any
fileSize. Let's refresh and let me now quickly find some big file. I should have it somewhere. So let's say this one 126 MB, open and here we go. You was able to see to still fast. Okay, there we go, but if we are checking this on some web hosting it will be much slower or if the
person doesn't have fast internet connection. But since we are checking this on a localhost this is extremely fast. So this part has been completed to. And
now here in order to make this one I will just go and quickly write the PHP code.
So at the top of this file I'm going to say php if (isset(FILES ['attachments'])). We will execute this part of code. Which
means if we have requests that file is uploading we are going to executed this part of the code. So first I want to show you what is inside this variable files.
So I will say echo or var_dump($_FILES), and let's see and here I will just say echo
just it have nicely formatted. Let's make a test, go to the choose files
choose any file, let's say this one and let's see what the server responded,
index. And as you can see now here, there is a response we have attachment, which is
an array, associative array and also multidimensional and inside we have
name and insade name we have one array with index 0. And also we have type, we have
temporary name, size, etc. So, in order to get the name I will just say target file which is where we are going to save our file.basename and here I will say attachments, and here as you can see
attachments, after that we will say name and index 0. And I'm using
basename just to get the file name. And after that I will check
if (file_exists($targetFile)), we will say our message will be which will
represent the response. I will say status => 0 and the reason message I will say "File already
exists!". Else if (move_uploaded_file), which means, if we successfully move the file
from the temporary location to our upload folders. So, I will say FILES['attacments'], ['tmp_name'] [0], temporary name 0 to the location targetFile we will say $msg = array ("status" =>1), "msg" => "File Has Been Uploaded" and here I will say the path of the file is targetFile. Okay and the last thing
I will just say exit (json_encode($msg)). Okay and just here we can declare this
message. Okay, so now let's make a test. Choose
files, let's see this one index.php. And as you can see the response status 1, message "File Has Been Uploaded", path uploads. And let's try again. Okay, now
this file already exists. So, now the last thing that we need to finish is
file upload done. So let's now again check what is inside the data.
Let's make a test, choose files this one. And as you can see here now in the
console, it is an object and we have a lot of informations again, but what we are looking for is this one and response json. So, as you can see the messages is "File already exists" and the status is zero.
And that is exactly what we have created on the server side. So, how we are going
to access we will say data.jq here and .responseJSON.message.
We will say var status = data.responseJSON.status. And the same thing we will do for message. And we will say if
status = 1, means that file has been uploaded. We will get a path of the file, so I
will just say path and here I will display this file inside our files. So, I will say files.append or first let's say file.fadeIn, because
it's not files hidden right now and I will just say append one new paragraph and inside this paragraph, we are going to have one image, source. And the source of
this image will be our path, that we have returned by the server. Okay, and pretty
much that's it. Else let's say here else if status is not correct we will say error.html our message. And let's make a test.
So now, we go to choose files, choose the file, open and says file already exists. So, let's test another one, I will use this one, open and now the file has been
uploaded, the result is completed 100% and here's a preview of our file. What we
can do is I can just for this image define style width 100 pixels, height 100
pixels. So, let's just try it, again. Choose file, let choose some picture, let's say this one, open and now the file has been uploaded, completed 100% and here is a
preview. So, if we try again, say this one guy, open and it is uploaded. So guys pretty
much that's it. I hope that this is a very simple and easy to understand
tutorial. I hope that to like it, if you do please like it and share with your
friends and also if you have any questions, please ask in the comments
below. Take care!