ADS

Featured

Upload files with Javascript

Follow in this tutorial how to upload files to a server-side page using only jQuery and javascript object, without creating iframe or similar, using the xhr feature of Ajax, allowing the use of a progress bar and allowing multiple uploads on a single page.

This is similar with uploading files from Gmail.

Here is the code:

/* Requer jQuery */
/* Modo de usar:
 *  UploadData( $('input[type="file"]') );
*/
function UploadData(obj){
    var FormDataFilesUpload = new FormData(); // Cria formulário baseado em objeto JavaScript.
    /* Pega todos os arquivos do objeto passado pela função */
    $.each( $(obj)[0].files , function (index,file) { FormDataFilesUpload.append('data_file', file); }); // Attach all files on this form.
   
    $(obj).val(''); // Clears objects loaded on the physical element of the page.
   
    $.ajax({ // Starts ajax to transmit the files.
        url: 'upload.php?elementoGet=xptoValor',
        data: FormDataFilesUpload,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        beforeSend: function(){
       /*Area to enter code to execute before starting the ajax request. Ex .: Screen lock during upload. */
        },
        xhr: function(){  
        /* Xhr function for handling the download and upload of the Ajax form */
            var xhr = new window.XMLHttpRequest();
            /* Event log for upload progress */
            xhr.upload.addEventListener("progress", function(evt){
              if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
                /* You can make use of the variable below to display progress */
                $('.progresso').css({width:percentComplete*100 +'%'});
               
              }
            }, false);
            /* Registration for download event */
            xhr.addEventListener("progress", function(evt){
              if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
                /* Download progress */
                $('.progresso').css({width:percentComplete*100 +'%'});
               
              }
            }, false);
           
            return xhr;
        },
        success: function (data) {
        /* Upon successful uploading */
            $('.progresso').css({width:'0%'});
        },
        fail: function (data) {
        /* Upon completion of upload with error */
           
            $('.progresso').css({width:'0%'});
        }
    }); /* ajax */
}

No comments