4

I am trying to upload an image using AJAX. I have the local URL of my image and I want to pass that image as a file to the web service to upload.

Suppose i have the local file URL as : file:///accounts/1000/shared/camera/IMG_00000322.jpg

Now using AJAX I want to pass this to webservice, What will be the best way to do this? I also want show the progress while uploading

Using php in server side.

uploadImage : function(myImageUrl,chatId){

    var formData = new FormData();
    formData.append("chatId", chatId);
    formData.append("fileimage", myImageUrl);

        $.ajax(
        {
            type:"POST",
            url:"http://suresh.sp.in/butler/public/uploadimage/getimage",
            contentType:"image/png",
            dataType:"json",
            data:formData,
            success:function(uploaded){
                console.info(uploaded.status);
            },
            error:function(error){
                                    console.info(error);    

            }
        });

}
2
  • This may be helpful : github.com/blueimp/jQuery-File-Upload Commented Mar 5, 2014 at 7:14
  • convert image into string and encrypt that string value and send it to web service.In web service side decrypt and move the image Commented Mar 5, 2014 at 7:21

1 Answer 1

1

I used that snippet on several of my websites, it handles Multiples files upload, drag and drop, and a progress bar.

HTML

You will need a container to drop your batch of files, in our case it will be #output, and a list of files.

JS

First we will push the dataTransfer to jQuery's event and bind the drop event.

$(document).ready(function(){
    // We add the dataTransfer special property to our jQuery event
    $.event.props.push("dataTransfer");
    
    // We bind events for drag and drop
    $('#output').bind({
        "dragenter dragexit dragover" : do_nothing,
        drop : drop
    }); 
    
});
// stop event propagation
function do_nothing(evt){
    evt.stopPropagation();
    evt.preventDefault();
}

Then we build our update progress function

// Progress bar update function
function update_progress(evt,fic) {
    
    var id_tmp=fic.size;
    //id_tmp help us keep track of which file is uploaded
    //right now it uses the filesize as an ID: script will break if 2 files have the     
    // same size
    if (evt.lengthComputable) {
        var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
        if (percentLoaded <= 100) {
            $('#'+id_tmp+' .percent').css('width', percentLoaded + '%');
            $('#'+id_tmp+' .percent').html(percentLoaded + '%');
        }
    }
}

Last but not least our drop function

function drop(evt){
    do_nothing(evt);
        
    var files = evt.dataTransfer.files;
    
    // Checking if there are files
    if(files.length>0){
        for(var i in files){
            // if its really a file
            if(files[i].size!=undefined) {
                
                var fic=files[i];
                
                // We add a progress listener
                xhr = jQuery.ajaxSettings.xhr();
                if(xhr.upload){
                    xhr.upload.addEventListener('progress', function (e) {
                        update_progress(e,fic);
                    },false);
                }
                provider=function(){ return xhr; };
                
                // We build our FormData object
                var fd=new FormData;
                fd.append('fic',fic);
                
                // For each file we build and Ajax request
                $.ajax({
                    url:'/path/to/save_fic.php',
                    type: 'POST',
                    data: fd,
                    xhr:provider,
                    processData:false,
                    contentType:false,
                    complete:function(data){ 
                        //on complete we set the progress to 100%
                        $('#'+data.responseText+' .percent').css('width', '100%');
                        $('#'+data.responseText+' .percent').html('100%');
                    }
                });
                        
                
                // for each file we setup a progress bar
                var id_tmp=fic.size;
                $('#output').after('<div class="progress_bar loading" id="'+id_tmp+'"><div class="percent">0%</div></div>');
                $('#output').addClass('output_on');
                
                // We add our file to the list
                $('#output-listing').append('<li>'+files[i].name+'</li>');
                
            }
        }
    }

}

That method doesn't work in IE9 or below. Hope it helped! Source(in french)

Some infos on progress tracking using XMLHttpRequest

Some infos on the datatransfer prop

EDIT:

PHP

From the server side you can handle the files normally using $_FILES etc... In order to set the progress to 100% in the complete function your php script must echo the filesize.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Let Me try this first :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.