Akanksha Mohanty
Akanksha Mohanty

Reputation: 701

File Upload ajax call - Send the file only after clicking on Submit button

FIle upload process -

When we select a file from the system it runs the follwing process:

  1. It checks whether the file had the defined types or not if not then stop the file upload.
  2. When we select a file from the system then it adds a progress bar that informs about the percentage of file uploading progress.
  3. Along with file progress bar it adds a cancel button, If you want to cancel the file upload in between the progress.
  4. If the file is loaded 100% then show the success message with the KB/MB of file. Here file is not uploaded that means not sent through Ajax call.
  5. Along with loaded 100% message show a Remove button. If a user want to remove the file then he can remove the file and then select the another file from the system.
  6. Submit button action - On clicking on Submit button the Ajax call should fire and save the file to the defined loaction. Here I have used PHp to send file to the definde location.

The issue I am facing is - I want to perform the action from 1 to 5 (above mentioned numbers) without any ajax call. on clicking of the submit button then only the data should save otherwise it should not save.

In my case the file is getting save when it is loaded 100%. so If I click on remove button the file is already sent to the defined location.

How can I perform the onclick on submit button.

Below is the code -

HTML -

 <section class="bulk-upload--sec">
        <form action="#">
            <label for="ccp-bulkupload__btn" class="ccp-bulkupload__label">Upload File</label>
            <input type="file" id="ccp-bulkupload__btn" name="file" class="file-input" hidden>
        </form>
        <section class="progress-area"></section>

        <section class="uploaded-area"></section>
       
        <button class="btn btn-primary btn-submit" type="submit">Submit</button>
    </section>

CSS -

 body{
            position: relative;
            color: #000;
        }
        .bulk-upload--sec{
            position: absolute;
           top: 150px;
           left: 150px;
        }
        form label{
            cursor: pointer;
        }
        .progress-bar{
            height: 6px;
            width: 100%;
            background: #d8d8d8;
            margin-bottom: 4px;
        }
        .progress--1{
            height: 100%;
            width: 10%;
            background: #6990f2;
            border-radius: inherit;
        }
        .upload-status{
            color: #000;
        }
        .disabled{
            color: #ddd;
            cursor: default;
        }
        .ccp-bulkupload__label{
            cursor: pointer;
            border-radius: 0;
            border: 1px solid #5e10b1;
            height: 50px;
            width: 180px;
            color: #5e10b1;
            text-align: center;
        }

JS-

let filArray = [];
let ajaxCall;

$('.btn-submit').on('click', function(e){
    e.preventDefault();
    alert("I am done");
})


$('.file-input').on('change', function({target}){
    let file = target.files[0];
    let allowedTypes = ['application/pdf', 'application/csv', 'application/vnd.ms-excel'];
    let fileType = file.type;

    console.log("target", file);

        if(file && allowedTypes.includes(fileType)){
            let fileName = file.name;
            if(fileName.length >= 12){
                let splitText = fileName.split('.');
                console.log("splitText",splitText);
                fileName = splitText[0].substring(0, 12) + '..' + splitText[1];
            }
            uploadFile(fileName);
            fileStorage(file);
        }else{
            console.log("cannot save");
            filArray.pop();
            $('.fileType').val('');
            return false;
        }
    
});
function fileStorage(arr){
    filArray.push(arr);
    console.log("file array", filArray);
}
function uploadFile(name){
    ajaxCall = $.ajax({
        xhr: function(){
            let xhr = new XMLHttpRequest();
            xhr.upload.addEventListener("progress", ({loaded, total}) =>{
                console.log("loaded, total",loaded, total);
                let fileLoaded = Math.floor((loaded / total) * 100);
                let fileTotal = Math.floor(total / 1000);
            
                let fileSize;
                
                fileSize = (fileTotal < 1024) ? fileSize = fileTotal + 'KB' : fileSize = (loaded / (1024 * 1024)).toFixed(2) + 'MB';

            
                let progressHtml = `<div class="row"><div class="details"><span class="name"> ${name}</span><span>- </span></div><div class="progress-bar"><div class="progress--1" style="width:${fileLoaded}%"></div></div></div>`
                progressHtml += `<div class="upload-status"><span class="uploading-status">Uploading</span><span class="percentage">${fileLoaded}%</span></div></div>`
                progressHtml += `<button class="btn btn-danger btn-cancel">Cancel</button>`
                $('.progress-area').html(progressHtml);

      

                if(loaded == total){
                    $('.progress-area').html('');
                    let uploadedHTML = `<div class="row"> <div class="uploaded"><div class="details"><span class="name"> ${name}</span><span>- </span> <p>Uploaded .<span class="size">${fileSize}</span></p></div></div><div class="success-msg"><p>Successfull!!</p></div></div>`
                    uploadedHTML += `<button class="btn btn-sucess btn-remove">Remove</button>`
                    $(".uploaded-area").html(uploadedHTML);   
                }

                $('.btn-cancel').on('click', function(){
                    ajaxCall.abort();
                    filArray.pop();
                    $('form')[0].reset();
                    $('.fileType').val('');
                    $('.progress-area').html('');
                })
                $('.btn-remove').on('click', function(){
                    filArray.pop();
                    $('form')[0].reset();
                    $('.file-input').val('');
                    $('.uploaded-area').html('');
                    alert("file is removed");
                    console.log("cleared array", filArray);
                })
    
            }, false);
            return xhr;
        },
        // Your server script to process the upload
        type: 'POST',
        url: "php/uploaded.php",
        //formData
        data: new FormData($('form')[0]),
        cache: false,
        contentType: false,
        processData: false,
        error: function(){
            alert("This is an error");
        },
        success: function(){
           alert("successfull");
        }
    
    })
}

PHP -

<?php
$file_name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$file_up_name = time().$file_name;
move_uploaded_file($tmp_name, "files/".$file_up_name);
?>

Upvotes: 1

Views: 1015

Answers (1)

akicsike
akicsike

Reputation: 386

When a file is selected, then perform just the check and store the file in variable. After when the submit button is clicked, then call the ajax for upload.

let filArray = [];
let ajaxCall;
let fileName = "";

$('.btn-submit').on('click', function(e){
    e.preventDefault();
    uploadFile(fileName);   // change <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    alert("I am done");
})


$('.file-input').on('change', function({target}){
    let file = target.files[0];
    let allowedTypes = ['application/pdf', 'application/csv', 'application/vnd.ms-excel'];
    let fileType = file.type;

    console.log("target", file);

        if(file && allowedTypes.includes(fileType)){

            fileName = file.name;  // change <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
            if(fileName.length >= 12){
                let splitText = fileName.split('.');
                console.log("splitText",splitText);
                fileName = splitText[0].substring(0, 12) + '..' + splitText[1];
            }

            fileStorage(file);
        }else{
            console.log("cannot save");
            filArray.pop();
            $('.fileType').val('');
            return false;
        }
    
});
function fileStorage(arr){
    filArray.push(arr);
    console.log("file array", filArray);
}
function uploadFile(name){
    ajaxCall = $.ajax({
        xhr: function(){
            let xhr = new XMLHttpRequest();
            xhr.upload.addEventListener("progress", ({loaded, total}) =>{
                console.log("loaded, total",loaded, total);
                let fileLoaded = Math.floor((loaded / total) * 100);
                let fileTotal = Math.floor(total / 1000);
            
                let fileSize;
                
                fileSize = (fileTotal < 1024) ? fileSize = fileTotal + 'KB' : fileSize = (loaded / (1024 * 1024)).toFixed(2) + 'MB';

            
                let progressHtml = `<div class="row"><div class="details"><span class="name"> ${name}</span><span>- </span></div><div class="progress-bar"><div class="progress--1" style="width:${fileLoaded}%"></div></div></div>`
                progressHtml += `<div class="upload-status"><span class="uploading-status">Uploading</span><span class="percentage">${fileLoaded}%</span></div></div>`
                progressHtml += `<button class="btn btn-danger btn-cancel">Cancel</button>`
                $('.progress-area').html(progressHtml);

      

                if(loaded == total){
                    $('.progress-area').html('');
                    let uploadedHTML = `<div class="row"> <div class="uploaded"><div class="details"><span class="name"> ${name}</span><span>- </span> <p>Uploaded .<span class="size">${fileSize}</span></p></div></div><div class="success-msg"><p>Successfull!!</p></div></div>`
                    uploadedHTML += `<button class="btn btn-sucess btn-remove">Remove</button>`
                    $(".uploaded-area").html(uploadedHTML);   
                }

                $('.btn-cancel').on('click', function(){
                    ajaxCall.abort();
                    filArray.pop();
                    $('form')[0].reset();
                    $('.fileType').val('');
                    $('.progress-area').html('');
                })
                $('.btn-remove').on('click', function(){
                    filArray.pop();
                    $('form')[0].reset();
                    $('.file-input').val('');
                    $('.uploaded-area').html('');
                    alert("file is removed");
                    console.log("cleared array", filArray);
                })
    
            }, false);
            return xhr;
        },
        // Your server script to process the upload
        type: 'POST',
        url: "php/uploaded.php",
        //formData
        data: new FormData($('form')[0]),
        cache: false,
        contentType: false,
        processData: false,
        error: function(){
            alert("This is an error");
        },
        success: function(){
           alert("successfull");
        }
    
    })
}

Upvotes: 1

Related Questions