我有一个关于fopen()和base64通信的问题。 场景是:我有一个必须从url获取资源(png / jpeg或pdf)的服务A.代码是:
$uri = urldecode($_POST['uri']);
$imgfile = $uri;
$handle = fopen($uri, 'r');
$imagebinary = '';
while (!feof($handle)) {
$c = fgetc($handle);
if($c === false) break;
$imagebinary .= $c;
}
fclose($handle);
$return = base64_encode($imagebinary);
现在我有JQUERY函数将这个$ return(类似的东西:'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA B服务获取此字符串并尝试将其保存在磁盘上。具体来说,服务B尝试将文件保存在amazon s3上,代码为:
// in $imagedata is saved the string generated by service A
$imagedata = $_POST['serviceA_base64encodedfile'];
// $contentType taken from switch function on $ext
// for example 'image/png'
$filename = sha1(uniqid()) . '.' . $ext;
$full_filename = $path . '/' . $filename;
$stream = fopen('data://' . $contentType . ';base64,' . $imagedata, 'r');
fseek($stream, 0);
$opt = array(
'fileUpload' => $stream,
'acl' => AmazonS3::ACL_PUBLIC,
'contentType' => $contentType
);
$s3 = new AmazonS3(AWS_KEY, AWS_SECRET_KEY);
$response = $s3->create_object($bucket, $filename, $opt);
但是保存的图像已损坏,此外此图像或pdf的原始字节数更少。
我需要真正的帮助:D
答案 0 :(得分:2)
我不是100%确定这会起作用,但为什么不将数据base64_decode重新编码为二进制,然后将数据写入临时文件并从该位置发送到amazon。像(未经测试)的东西:
// in $imagedata is saved the string generated by service A
$imagedata = base64_decode($_POST['serviceA_base64encodedfile']);
if (!$imagedata){
//Handle invalid base64 encoded data
}
// $contentType taken from switch function on $ext
// for example 'image/png'
$filename = sha1(uniqid()) . '.' . $ext;
$full_filename = $path . '/' . $filename;
$tmpfname = tempnam("/tmp", "image_to_upload");
$populated = file_put_contents($tmpfname,$imagedata);
if (!$populated){
//handle write failures
}
$opt = array(
'fileUpload' => "/tmp/".$tmpfname,
'acl' => AmazonS3::ACL_PUBLIC,
'contentType' => $contentType
);
$s3 = new AmazonS3(AWS_KEY, AWS_SECRET_KEY);
$response = $s3->create_object($bucket, $full_filename, $opt);
我还假设在最后一次调用时,$ full_filename是您要将文件存储在s3服务器上的位置...尽管您可以使用$ file_name。