使用带有进度指示器的AJAX上传图像

时间:2014-03-05 07:09:08

标签: javascript php jquery ajax

我正在尝试使用AJAX上传图片。我有我的图像的本地URL 我希望将该图像作为文件传递给要上传的Web服务。

假设我的本地文件URL为:file:///accounts/1000/shared/camera/IMG_00000322.jpg

现在使用AJAX我想把它传递给webservice, 最好的方法是什么?我还想在上传时显示进度

在服务器端使用php。

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);    

            }
        });

}

1 个答案:

答案 0 :(得分:1)

我在我的几个网站上使用了该片段,它处理Multiples文件上传,拖放和进度条。

<强> HTML

您将需要一个容器来删除您的批处理文件,在我们的例子中它将是#output和文件列表。

<强> JS

首先,我们将dataTransfer推送到jQuery的事件并绑定drop事件。

$(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();
}

然后我们构建更新进度函数

// 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 + '%');
        }
    }
}

最后但并非最不重要的是我们的掉落功能

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>');

            }
        }
    }

}

该方法在IE9或更低版本中不起作用。 希望它有所帮助! Source(in french)

Some infos on progress tracking using XMLHttpRequest

Some infos on the datatransfer prop

编辑:

<强> PHP

从服务器端,您可以使用$ _FILES等正常处理文件... 为了在完整函数中将进度设置为100%,您的php脚本必须回显文件大小。

相关问题