将base64图像发布到php

时间:2013-06-06 07:08:55

标签: php jquery image post base64

我想通过Jquery AJAX在php脚本中发布一个base64图像文件..

我已经使用Jquery的encodeURIComponent()函数对其进行了编码,然后在发布数据时使用php上的rawurldecode()函数对其进行解码。

问题是,Php无法将正确的图像保存到png。

我比较了发布的base64数据和原始数据,但它们并不匹配。这让我得出结论,也许base64数据太大而无法发布。

我的结论是真的吗?如果是的话,还有其他方法可以成功发布base64数据吗? 如果我错了,你能请教导我吗?

这是Jquery脚本

var whereSignatureis = $('.signatureView');

// i got the image from a plugin called jSignature, assign it to a variable data.
var data = signPaper.jSignature("getData","image");
// created an image ddata from what the data returned for displaying purposes.
var ddata = new Image();
// the ddata.src is now the png base64 image
ddata.src = "data:" + data[0] + "," + data[1];
// I encoded the image with uricomponent for safe posting.
var theImg = encodeURIComponent(ddata.src);
// and posted the image
$.ajax({
        type: "POST",
        url: "processes.php",
        data: {img: theImg},
        contentType: "application/x-www-form-urlencoded;charset=UTF-8",
        success: function(r){
            whereSignatureis.append(r);
        }
    });

这是Php

define('UPLOAD_DIR', '/images');


$img = rawurldecode($post->img);
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . 'signature' . '.png';
$success = file_put_contents($file, $data);
print $success ? "{$post->img}" : 'File not Saved.';

提前致谢!

1 个答案:

答案 0 :(得分:1)

我发现在发送之前尝试编码到base64文本只会导致问题,因为JavaScript URI编码函数用加号替换了base64字符串中的所有空格,从而破坏了图像。我会完全删除encodeURIComponent()函数,它应该可以工作。