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条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 多电路系统共用电源的串扰问题
    • ¥15 shape_predictor_68_face_landmarks.dat
    • ¥15 slam rangenet++配置
    • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
    • ¥15 对于相关问题的求解与代码
    • ¥15 ubuntu子系统密码忘记
    • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
    • ¥15 保护模式-系统加载-段寄存器
    • ¥15 电脑桌面设定一个区域禁止鼠标操作
    • ¥15 求NPF226060磁芯的详细资料