javascript - Ajax send & Save Base64 encoded image to server - Stack Overflow

I am passing a base64 url through jquery ajax and want to save onto the server. But the code below is g

I am passing a base64 url through jquery ajax and want to save onto the server. But the code below is giving me a empty file. I have tried writing the decoded string and createimage from string but with both variables, 0 bites have been written. When i test the value being worked on it outputs [object FileReader]......i think either i am missing a step or making a mistake some where.

Also is there a way to convert the image to a $_FILE type object? reason being id like to using a wordpress function to save the file if possible.

Php code:

function uploadimg() {

$error = false;
//if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
//$upload_overrides = array( 'test_form' => false );
$images=array();

$a=0;
unset ($_POST['action']);

foreach($_POST as $basefile){


    $upload_dir       = wp_upload_dir();
    $upload_path      = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;
    $base64_string = $basefile; 
    echo $basefile;
    $base64_string = preg_replace( '/data:image\/.*;base64,/', '', $base64_string ); 
    $decoded_string= base64_decode($base64_string); // 0 bytes written in fwrite
    $source = imagecreatefromstring($decoded_string); // 0 bytes written in fwrite
    $output_file = $upload_path.'myfilef'.$a.'.jpg'; 
    $images[]=$output_file;
    $a++;       
    $image = fopen( $output_file, 'wb' ); 

    $bytes=fwrite( $image, $source); 
    echo $bytes;
    fclose( $image ); 
}
 echo json_encode($images);
 exit;

 }

add_action('wp_ajax_uploadimg', 'uploadimg');
add_action('wp_ajax_nopriv_uploadimg', 'uploadimg');

jQuery sample code

jQuery(document).on('change', '.imageup', function(event){
    errors= [];
    errnum=0;
    numberofimages=jQuery("#selectedimages > div").length; //get number of images

    if(numberofimages<10){

        var id= jQuery(this).attr('id');
        var length= this.files.length;

        if(length>1) {// if a multiple file upload

        var images = new FormData();
        images.append('action', 'uploadimg'); //wordpress specific

            jQuery.each(event.target.files, function(key, value ){


                var size= value.size;

                var extension= value.name.substring(value.name.lastIndexOf('.') + 1).toLowerCase();
                var allowedExtensions = ['png', 'jpg', 'jpeg', 'gif'];
                if( allowedExtensions.indexOf(extension) !== -1 ) {

                if(numberofimages<10){

                var file=value;
                console.log(file);
                var fileReader = new FileReader();


                    fileReader.onload = function (e) {
                        var img = new Image();


                        img.onload = function () {
                            var MAX_WIDTH = 100;
                            var MAX_HEIGHT = 100;
                            var width = img.width;
                            var height = img.height;

                            if (width > height) {
                            if (width > MAX_WIDTH) {
                            height *= MAX_WIDTH / width;
                            width = MAX_WIDTH;
                            }
                        } else {
                    if (height > MAX_HEIGHT) {
                        width *= MAX_HEIGHT / height;
                    height = MAX_HEIGHT;
                    }
        }

        var canvas = document.createElement("canvas");
        canvas.width = width;
        canvas.height = height;
        canvas.getContext("2d").drawImage(this, 0, 0, width, height);

        this.src = canvas.toDataURL('image/png');

    } // end on load function

    img.src = e.target.result;

} //end filereader function

fileReader.readAsDataURL(file);
console.log(fileReader);

                    images.append(key, fileReader);
                        numberofimages++;


                } else {
                        errnum++;
                        errors[errnum]= value=' is a illegal file type';
                    }
                }           


            });

        //image holder finished, remove
        jQuery('#'+id).remove();


        jQuery.ajax({
            url: '/wp-admin/admin-ajax.php',
            type: 'POST',
            data: images, 
            cache: false,
            processData: false, 
            contentType: false, 
                success: function(data) {
                    console.log(data);
            }//end of success function
        });

I am passing a base64 url through jquery ajax and want to save onto the server. But the code below is giving me a empty file. I have tried writing the decoded string and createimage from string but with both variables, 0 bites have been written. When i test the value being worked on it outputs [object FileReader]......i think either i am missing a step or making a mistake some where.

Also is there a way to convert the image to a $_FILE type object? reason being id like to using a wordpress function to save the file if possible.

Php code:

function uploadimg() {

$error = false;
//if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
//$upload_overrides = array( 'test_form' => false );
$images=array();

$a=0;
unset ($_POST['action']);

foreach($_POST as $basefile){


    $upload_dir       = wp_upload_dir();
    $upload_path      = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;
    $base64_string = $basefile; 
    echo $basefile;
    $base64_string = preg_replace( '/data:image\/.*;base64,/', '', $base64_string ); 
    $decoded_string= base64_decode($base64_string); // 0 bytes written in fwrite
    $source = imagecreatefromstring($decoded_string); // 0 bytes written in fwrite
    $output_file = $upload_path.'myfilef'.$a.'.jpg'; 
    $images[]=$output_file;
    $a++;       
    $image = fopen( $output_file, 'wb' ); 

    $bytes=fwrite( $image, $source); 
    echo $bytes;
    fclose( $image ); 
}
 echo json_encode($images);
 exit;

 }

add_action('wp_ajax_uploadimg', 'uploadimg');
add_action('wp_ajax_nopriv_uploadimg', 'uploadimg');

jQuery sample code

jQuery(document).on('change', '.imageup', function(event){
    errors= [];
    errnum=0;
    numberofimages=jQuery("#selectedimages > div").length; //get number of images

    if(numberofimages<10){

        var id= jQuery(this).attr('id');
        var length= this.files.length;

        if(length>1) {// if a multiple file upload

        var images = new FormData();
        images.append('action', 'uploadimg'); //wordpress specific

            jQuery.each(event.target.files, function(key, value ){


                var size= value.size;

                var extension= value.name.substring(value.name.lastIndexOf('.') + 1).toLowerCase();
                var allowedExtensions = ['png', 'jpg', 'jpeg', 'gif'];
                if( allowedExtensions.indexOf(extension) !== -1 ) {

                if(numberofimages<10){

                var file=value;
                console.log(file);
                var fileReader = new FileReader();


                    fileReader.onload = function (e) {
                        var img = new Image();


                        img.onload = function () {
                            var MAX_WIDTH = 100;
                            var MAX_HEIGHT = 100;
                            var width = img.width;
                            var height = img.height;

                            if (width > height) {
                            if (width > MAX_WIDTH) {
                            height *= MAX_WIDTH / width;
                            width = MAX_WIDTH;
                            }
                        } else {
                    if (height > MAX_HEIGHT) {
                        width *= MAX_HEIGHT / height;
                    height = MAX_HEIGHT;
                    }
        }

        var canvas = document.createElement("canvas");
        canvas.width = width;
        canvas.height = height;
        canvas.getContext("2d").drawImage(this, 0, 0, width, height);

        this.src = canvas.toDataURL('image/png');

    } // end on load function

    img.src = e.target.result;

} //end filereader function

fileReader.readAsDataURL(file);
console.log(fileReader);

                    images.append(key, fileReader);
                        numberofimages++;


                } else {
                        errnum++;
                        errors[errnum]= value=' is a illegal file type';
                    }
                }           


            });

        //image holder finished, remove
        jQuery('#'+id).remove();


        jQuery.ajax({
            url: '/wp-admin/admin-ajax.php',
            type: 'POST',
            data: images, 
            cache: false,
            processData: false, 
            contentType: false, 
                success: function(data) {
                    console.log(data);
            }//end of success function
        });
Share Improve this question edited Jul 7, 2015 at 14:03 David asked Apr 27, 2014 at 13:10 DavidDavid 5,9373 gold badges25 silver badges44 bronze badges 5
  • readAsDataURL is asynchronous, when it pletes successfully, the load event will fire on fileReader, and the result of readAsDataURL will be in the result property. See FileReader on MDN for more reading. – Paul S. Commented Apr 27, 2014 at 13:25
  • onload is included in the proper jquery code......i updated above with more..... – David Commented Apr 27, 2014 at 13:31
  • I don't see how you're waiting for the onload before sending after the loop finishes – Paul S. Commented Apr 27, 2014 at 14:10
  • hmm i see what you mean.....any idea of a method to wait for the variable amount of values? – David Commented Apr 27, 2014 at 21:16
  • actually should be ok now, ill update a answer when i finish it. work in progress if anyone has ments jsfiddle/dheffernan/6Ut59 – David Commented Apr 28, 2014 at 1:07
Add a ment  | 

1 Answer 1

Reset to default 1

ok thanks to PaulS for pointing me in the right direction....updated jQuery below........the php up top wont work with this (im cutting out the ajax even though i have included a note below to show where it goes) the array is different as i added in the filename as well as the base64 url.

jsfiddle http://jsfiddle/dheffernan/6Ut59/

Basically the flow is, 1.Check max files allowed 2 & then for each file check it does not exceed it.
3 Call filereader, when loaded, call resizeBase64img (thanks to the person who submitted that) 4. if on the last file to be processed -- submit FormData via Ajax 5.When file returns input div to show image & if full remove file input

function resizeBase64Img(base64, width, height) {
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");
var deferred = $.Deferred();
$("<img/>").attr("src", base64).load(function() {
    context.scale(width/this.width,  height/this.height);
    context.drawImage(this, 0, 0); 
    deferred.resolve($("<img/>").attr("src", canvas.toDataURL('image/jpg')));               
});
return deferred.promise();    
}



function readFile(file) {
var reader = new FileReader();
var deferred = $.Deferred();

reader.onload = function(event) {
    deferred.resolve(event.target.result);
};

reader.onerror = function() {
    deferred.reject(this);
};

if (/^image/.test(file.type)) {
    reader.readAsDataURL(file);
} else {
    reader.readAsText(file);
}

return deferred.promise();
}

jQuery(document).on('change', '.imageup', function(event){
var maximages=4;
var imagecount=jQuery("#imagesholder > div").length;
var length= this.files.length;
var images= new FormData;
var processKey=0;
var i=1;
jQuery.each(event.target.files, function(key, value){
    // number of images control. 
    imagecount++;
    if(imagecount > maximages) {
        var full=true;
        jQuery('.imageup').remove();
        jQuery('#imageinput').html("Image Quota Full, Please delete some images if you wish to change them");
        return;   
    } else if (imagecount == maximages) {
        var full=true;
        jQuery('.imageup').remove();
        jQuery('#imageinput').html('<div class="image-box-full">Image Quota Full: delete images to change them</div>');   
    }

    //call resize functions
    var name=value;
    $.when( readFile(value) ).done(function(value) {

        resizeBase64Img(value, 300, 200).done(function(newImg){
             images[processKey]=[];
             images[processKey]['url']=newImg[0].src;
             images[processKey]['name']=name.name;
             processKey++;

 if(length===processKey) {
 //----------------INSERT AJAX TO RUN HERE SUBMITTING IMAGES (THE FORMDATA) E.G
 jQuery.ajax({
            url: '/wp-admin/admin-ajax.php',
            type: 'POST',
            data: images, 
            cache: false,
            processData: false, 
            contentType: false, 
                success: function(data) {
                    console.log(data);
                    }
        });
 }

 $('#imagesholder').append('<div id="delete'+i+'">'+'<div class="image-box"><div class="box-image"><img src="'+newImg[0].src+'" style="width:50px;"/></div><div class="image-box-text">'+name.name+'</div><input type="image" src="http://testserverdavideec.mx.nf/wp-content/uploads/2014/04/success_close.png" class="deletebutton"  id="delete/i'+i+'"/></div>  </div>');

i++;

            if(full === true) {
             jQuery('.image-box-full').show();   
            }
        });

    });//end when

 });//end each

 jQuery(this).val('');   
 });//end on change

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745036557a4607554.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信