drq231358 2017-05-23 16:40
浏览 1132

解码时base64_decode失败

I'm trying to send an image from user's computer using an input (file). I resize the image using a canvas and then get a base64 string encoded via the toDataURL method of the canvas.

Then I send the encoded string to my server via an AJAX request. In PHP, I receive properly the POST data, but it fails when I want to use the base64_decode to save the encoded string into a file on my server.

CLIENT SIDE :

function upload_document(file){

    var url_post_document = "url_to_server";
    var type_img = file.type;
    var reader = new FileReader();

    reader.onload = function(evt){

    var image = document.createElement('img');
    image.onload = function (){ 

        var canvas = document.createElement('canvas');
        canvas.height = 40;
        canvas.width = 40;
        var ctx = canvas.getContext('2d');

        ctx.drawImage(this, 0, 0, 40, 40);

        var shrinked = canvas.toDataURL(file.type);
        //console.log(shrinked);

        $.ajax({
            url: url_post_document,
            type: 'POST',
            xhrFields: {
                withCredentials: false
            },  
            data: {
                "user_id": user_id,
                "image": shrinked,
                "image_type": type_img
            },
            success: function(data) {
                console.log("RESPONSE");
                console.log(data);
            },
            error: function() {
                console.log("----- FAIL -----");
            },
            complete: function() {
                console.log("----- REQUEST COMPLETED -----");
            }
        });
     };

     image.src = reader.result;

     };

    reader.readAsDataURL(file);
}

SERVER SIDE :

if(isset($_POST['user_id'])){

        $extension = explode('/', $_POST['image_type']);
        $extension = $extension[1];
        define('UPLOAD_DIR', WP_CONTENT_DIR.'/uploads/userthumb/');

        $imgBaseData = rtrim($_POST['image']);
        $img        = str_replace('data:'.$_POST['image_type'].';base64,', '', $imgBaseData);
        $img        = str_replace(' ', '+', $img);

        $baseimage  = base64_decode($img, true);
        return $baseimage;
}

I tried to copy and past the base64 string got from the toDataURL method on an online base64decoder and it works, the image is displayed. But on the server, impossible to decode the string.

I would appreciate any help on this matter. Thanks in advance !

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥60 版本过低apk如何修改可以兼容新的安卓系统
    • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
    • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
    • ¥50 有数据,怎么用matlab求全要素生产率
    • ¥15 TI的insta-spin例程
    • ¥15 完成下列问题完成下列问题
    • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
    • ¥15 YoloV5 第三方库的版本对照问题
    • ¥15 请完成下列相关问题!
    • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?