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

Javascript 使用带有进度指示器的AJAX上传图像,javascript,php,jquery,ajax,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 FormDa

我正在尝试使用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);    

            }
        });

}

我在我的几个网站上使用了这个片段,它可以处理多个文件的上传、拖放和一个进度条

HTML

您将需要一个容器来放置您的批文件,在我们的例子中,它将是#输出,以及一个文件列表

JS

首先,我们将数据传输推送到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 + '%');
        }
    }
}
//进度条更新功能
功能更新进度(evt、fic){
变量id_tmp=fic.size;
//id\u tmp帮助我们跟踪上传的文件
//现在它使用文件大小作为ID:如果两个文件具有相同的大小,脚本将中断
//同样大小
if(evt.长度可计算){
var percentLoaded=数学轮((evt.loaded/evt.total)*100);
如果(百分比0){
for(文件中的变量i){
//如果它真的是一个文件
if(文件[i].size!=未定义){
var fic=文件[i];
//我们添加了一个进度侦听器
xhr=jQuery.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress',函数(e){
更新进度(e、fic);
},假);
}
provider=function(){return xhr;};
//我们构建FormData对象
var fd=新的FormData;
fd.追加('fic',fic);
//对于我们构建的每个文件和Ajax请求
$.ajax({
url:“/path/to/save_fic.php”,
键入:“POST”,
数据:fd,
xhr:提供程序,
processData:false,
contentType:false,
完成:函数(数据){
//完成后,我们将进度设置为100%
$('#'+data.responseText+'.percent').css('width','100%”);
$('#'+data.responseText+'.percent').html('100%);
}
});
//我们为每个文件设置一个进度条
变量id_tmp=fic.size;
$(“#输出”)。在('0%”之后;
$('#output').addClass('output#on');
//我们将文件添加到列表中
$(“#输出列表”).append(“
  • ”+文件[i].name+“
  • ”); } } } }
    这种方法在IE9或更低版本中不起作用。 希望有帮助!

    编辑:

    PHP

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

    这可能会有帮助:将图像转换为字符串,加密该字符串值并将其发送到web服务。在web服务端,请解密并移动图像。谢谢,让我先尝试一下:)
    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>');
                    
                }
            }
        }
    
    }