【问题标题】:Posting base64 image to php将base64图像发布到php
【发布时间】:2013-06-06 07:08:55
【问题描述】:

我想通过 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.';

提前致谢!

【问题讨论】:

  • 网址编码 != base64
  • 请发布一些代码,您如何处理 javascript 编码、发布和 php 解码
  • PHP在填写$_GET$_POST之前会自动解码查询字符串,你不需要自己调用rawurldecode()

标签: php jquery image post base64


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-02
    • 2016-05-07
    • 2018-04-02
    • 2013-02-04
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多