Upload files with jquery and progress bar

Hey guys, how are you? In today’s post we will see a very cool way to put a nice file upload form with progress bar using AJAX (JQuery).

To follow the post, I recommend reading this post , which is where I approach a php function to upload files safely and simply. It is this function that I will use in today’s example.To get started, download JQuery and the JQuery.Form plugin . That done, our directory and file structure should look like this:

  • index.php (Page where the form goes)
  • jquery.js (javascript plugin)
  • jquery.form.js (Jquery plugin for working with forms)
  • upload.js (Defines the rules of the asynchronous request)
  • send_file.php (Performs the file upload)
  • funcao_upload.php (Function to help upload)
  • uploads (Directory where files will be saved)

I emphasize that in our example we will only work with uploading images. But feel free to work with uploading any type of file.

Index.php file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
    <head>
        <title>www.rafaelwendel.com - Upload files with progress bar</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="jquery.js" type="text/javascript"></script>
        <script src="jquery.form.js" type="text/javascript"></script>
        <script src="upload.js" type="text/javascript"></script>
    </head>
    <body>
        <h1><a href="http://www.rafaelwendel.com" target="blank">www.rafaelwendel.com</a> - Upload files with progress bar</h1>
        <form name="formUpload" id="formUpload" method="post">
            <label>Choose the file: <input type="file" name="file" id="file" size="45" /></label>
            <br />
            <progress value="0" max="100"></progress><span id="percentage">0%</span>
            <br />
            <input type="button" id="btnSend" value="Send File" />
        </form>
        <div id="response">
 
        </div>
    </body>
</html>

In the header I include the 3 javascripts files that will be used. In the body, I insert a form of name / id “formUpload” and inside that form the field of type “file” called “file” .

Line 15 is where the progress bar goes , which initially has a value of 0% and which will be filled in automatically when the upload is being executed.

Then comes the “btnSend” button that will be responsible for submitting the form.

The “reply” div will be the location where we will display the messages returned by AJAX requests .

Now let’s go to the implementation of the upload.js file . It is in this file that we will define the rules for the asynchronous request to upload the file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$(document).ready(function(){
    $('#btnSend').click(function(){
        $('#formUpload').ajaxForm({
            uploadProgress: function(event, position, total, percentComplete) {
                $('progress').attr('value',percentComplete);
                $('#percentage').html(percentComplete+'%');
            },        
            success: function(data) {
                $('progress').attr('value','100');
                $('#percentage').html('100%');                
                if(data.success == true){
                    $('#response').html('<img src="'+ data.msg +'" />');
                }
                else{
                    $('#response').html(data.msg);
                }                
            },
            error : function(){
                $('#response').html('Error sending request!!!');
            },
            dataType: 'json',
            url: 'send_file.php',
            resetForm: true
        }).submit();
    })
})

We define the action in the button “btnSend” . When it is clicked, “formUpload” is submitted via AJAX request. This is where we define the rules using the parameters described below:

  • uploadProgess : responsible for managing upload progress (progress bar)
  • success: what to do in case of success (If everything goes well it displays in the “reply” div the image that was sent)
  • error : what to do in case of error (Displays an error message in the “response” div)
  • dataType : the type of data that will be used in the transmission of information (note that we use JSON in our example)
  • url: the server-side file that will be executed (In this case: send_file.php )
  • resetForm: reset the form at the end of execution

Now all that is missing is the file send_file.php which is responsible for doing the work itself of uploading the file “under the hood”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
/* Imports the file where the upload function is implemented */
require_once('funcao_upload.php');
 
/* Captura o arquivo selecionado */
$file = $_FILES['file'];
 
/*Defines valid file types (In our case, only images)*/
$types = array('jpg', 'png', 'gif', 'psd', 'bmp');
 
/* Calls the function to send the file */
$send = uploadFile($file, 'uploads/', $types);
 
$data['success'] = false;
 
if($send['erro']){    
    $data['msg'] = $send['erro'];
}
else{
    $data['success'] = true;
 
    /* File path */
    $data['msg'] = $send['caminho'];
}
 
/* Encodes the $data array variable into JSON format */
echo json_encode($data);

It uses the uploadFile function that is implemented in funcao_upload.php. Information the success or error are stored in a array in the end is encoded to the format JSON so the javascript to be able to receive them and use them.

And period. Test your form. If everything goes correctly, after the upload is complete, the image will be displayed on the screen.

To download the post files, click here.

If in doubt, use the comments box.

Hugs!!

He has a degree in Information Systems, a postgraduate degree in Database Systems and a master's degree in Education with a focus on Sociocommunity Technologies. He works as a teacher of technical and technological education at the Federal Institute of Education, Science and Technology of São Paulo, teaching subjects in the areas of programming, database, project development and software engineering.

Posts relacionados

Leave a Reply

Your email address will not be published. Required fields are marked *