Ajax请求内存不足

时间:2014-02-02 21:50:45

标签: php ajax html5

所以我正在制作这个项目,我必须制作一个照片共享网站,我选择照片然后上传它们,通过电子邮件发送链接,然后该人进入链接并下载照片。当我拍的照片很少而且不超过100MB的数据时,一切都很好,当我超越时,一切都变得不稳定。

我首先使用HTML5的FileReader()。逻辑如下: 我使用FileReader()将每张照片转换为base64代码,每3张照片转换后,我通过Ajax将{3}长base64字符串发送到php文件,然后将代码转换为照片和将它们上传到服务器上的文件夹中。

如果我选择了300张照片,则会执行100次ajax次请求。 如果我超过~150MB的数据ajax,第一个问题会给我uncaught exception out of memory错误。 第二个问题是,如果我选择超过20-30个文件,浏览器有时甚至会崩溃,甚至崩溃。

有什么建议我该怎么办?也许整个想法都是错的,我应该从其他地方开始,请帮忙。

这是代码:

//Forming the inputs
$(document).on("change","#fileUp",function(e){
            var file = null;
            var files = e.target.files; //FileList object
            var picReader = new FileReader();

            $(".eventPop").html("");
            $(".howMany").html("");

            $(".eventPop").show();
            $(".eventPop").append('<div class="adding"><img src="../public/cuts/uploading.gif" width="60px"></div>');

            countUp = parseInt(countUp) + parseInt(files.length);

            for(var i=0; i<=files.length-1; i++){

                file = files[i];

                var str = file.name.split(".")[0];

//
                //var picReader = new FileReader();

                if (file.type == "image/jpeg" || file.type == "image/png")
                {
                    picReader.addEventListener("load",function(event){
                            count++;

                            var picFile = event.target;

                            $(".photos").append("<input type='hidden' id='ph"+count+"' get='"+picFile.result+"' /> ");
                    });
                }
                else
                {
                    countUp--;
                }


                picReader.readAsDataURL(file);
            }

});


//actual ajax requests
$(document).on('click','.uploadImages',function(){

        info[1] = "4hold"+1 + Math.floor(Math.random() * 999999)+"_"+(new Date).getTime();
        $.ajax({
            type: "POST",
            url: "index/loadIntoDB",
            dataType:"text",
            data: {info: info},
            contentType: "application/x-www-form-urlencoded;charset=UTF-8",
            success: function(result){
            }
        });

        if (nrConfig > count)
        {
            nrConfig = count;
        }
        $(".eventPop").show();
        $(".eventPop").html("");
        $(".eventPop").append('<div class="adding"><p>Uploading files...'+( (nrConfig/count) * 100).toFixed(0)+'%</p></div>');
        for(var i=1; i<=parseInt(nrConfig)+1; i++)
        {
            if (i == parseInt(nrConfig)+1)
            {
                info[2] = info[2].substring(2, info[2].length);
                uploadImages(nrConfig,1);               
            }
            else
            {
                //info[0] = i+"-"+info[0];
                info[2] = info[2]+"--"+$("#ph"+i+"").attr("get");
            }
        }
    });


function uploadImages(i,d){
         info['3'] = i;
         info['4'] = d;

        $.ajax({
            type: "POST",
            url: "index/receiveImages",
            dataType:"json",
            data: {info : info },
            beforeSend : function (){
                //
            },
            contentType: "application/x-www-form-urlencoded;charset=UTF-8",
            success: function(result){
                for(index=result['leftOff']['1']; index <= result['info']['4']-1; index++)
                {
                    if (result[index]['filesize'] < 1000000)
                    {
                        result[index]['filesize'] = Math.floor(result[index]['filesize']/1000)+"kb";
                        $("#ph"+result[index]['id']).append("<div class='filesize'>"+result[index]['filesize']+"</div>");
                    }
                    else
                    {
                        result[index]['filesize'] = (result[index]['filesize']/1000000).toFixed(2)+"MB";
                        $("#ph"+result[index]['id']).append("<div class='filesize'>"+result[index]['filesize']+"</div>");
                    }
                    if (result[index]['filesize'].length > 0)
                    {
                        $("#ph"+result[index]['id']+" .uploading").remove();
                        $("#ph"+result[index]['id']).append("<img src='layout/cuts/check.png' title='Uploaded' class='done'>");
                        $("#ph"+result[index]['id']+" .upd").remove();
                    }
                }
                $(".eventPop").html("");
                $(".eventPop").append('<div class="adding"><p>Uploading files...'+( (result['info'][4]-1)/count * 100).toFixed(0)+'%</p></div>');

                if (((result['info'][4]-1)/count * 100).toFixed(0) == 100)
                {
                    setTimeout(function(){
                        $("progress").remove();
                        $(".eventPop").html("");
                        $(".eventPop").append("<div class='adding'>Upload complete!</div>");
                        setTimeout(function(){
                            $(".eventPop").html("");
                            $(".eventPop").append("<div class='adding'><div class='sendPhotos'><form action='#' onsubmit='return false;' method='post' enctype='multipart/form-data'><label>Your email</label><input type='text' class='yemail'/><br/><label>Friend's email</label><input type='text' class='fremail'/><br/><span class='tip'><div class='triangle'></div>You can send photos to multiple friends by typing their e-mail separated by ';'.<br/>Eg. 'thomas@gmail.com ; peter@gmail.com'</span><input type='submit' name='send' class='send' value='Send'></form></div></div>");
                        },1000);
                    },1000);
                }

                if (info[2].length)
                {
                    info[2] = "";
                }
                if ( (parseInt(result['info']['4'])+parseInt(nrConfig)) >= count )
                {
                    nrConfig = count-result['info']['4']+1;
                }

                if(result['info']['4'] <= count)
                {                   
                    for(i=result['info']['4']; i <= parseInt(result['info']['4'])+parseInt(nrConfig); i++)
                    {
                        if (i == parseInt(result['info']['4'])+parseInt(nrConfig))
                        {
                            info[2] = info[2].substring(2, info[2].length);
                            uploadImages(nrConfig,result['info']['4']);         
                        }
                        else
                        {
                            info[2] = info[2]+"--"+$("#ph"+i+"").attr("get");
                        }
                    }   
                }
            }
        });
    }

PHP代码:

public function receiveImages()
    {
        $string = strtok($_POST['info'][2],"--");
        $currentID = $_POST['info']['4'];
        $newArray['info']['3'] = $_POST['info']['3'];

        $newArray['leftOff']['1'] = $currentID;

        $phAdded = 0;

        while($string != false && $phAdded < $_POST['info']['3'])
        {
            $newArray[$currentID]['id'] = $currentID;
            $newArray[$currentID]['filesize'] = $this->saveImages($string,$_POST['info']['1'],$currentID);
            $currentID++;
            $phAdded++;
            $string = strtok("--");
        }

        $newArray['info']['4'] = $currentID;


        echo json_encode($newArray);
    }

public function saveImages($base64img = "",$folder = "",$currentID = "")
    {
        $newArray = array();

        if (!is_dir(UPLOAD_DIR.$folder))
        {
            mkdir(UPLOAD_DIR.$folder,0777);
        }
        $dir = UPLOAD_DIR.$folder."/";


        if (strstr($base64img,'data:image/jpeg;base64,'))
        {
            $base64img = str_replace('data:image/jpeg;base64,', '', $base64img);
            $uniqid = uniqid();
            $file = $dir . $uniqid . '.jpg';

            $file_name = $uniqid.".jpg";
        }
        else
        {
            $base64img = str_replace('data:image/png;base64,', '', $base64img);
            $uniqid = uniqid();
            $file = $dir . $uniqid . '.png';

            $file_name = $uniqid.".png";
        }

        $data = base64_decode($base64img);


        file_put_contents($file, $data);

        $size = filesize($file);
        if ($size > 1000000)
        {
            $size = number_format(($size/1000000),2)."MB";
        }
        else
        {
            $size = number_format(($size/1000),0)."kb";
        }

        return filesize($file);


    }

0 个答案:

没有答案