2012-01-11 43 views
1

我有一個關於fopen()和base64通信的問題。 這種情況是:我有一個服務A,必須從url中獲取資源(png/jpeg或pdf)。該代碼是:打開url和bytestream

$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); 

現在我有發送此$回報(類似的東西:「iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs」)jQuery函數到另一個PHP服務,命名爲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); 

但形象,被保存已損壞,在additionals這個圖片或PDF具有較少的字節,然後原單。

我真的需要幫助:d

+0

你可以做'$ imageninary = file_get_contents($ uri);'而不是做舊式的文件操作。這將更具可讀性,可能(或不可能)解決您的問題。 – 2012-01-11 14:43:32

+0

謝謝,我改變了所有我的fopen,但這不是方式..任何其他建議? – Matte 2012-01-11 15:06:29

回答

2

我不是100%肯定這會工作,但爲什麼不BASE64_DECODE的數據爲二進制,然後將數據寫入到一個臨時文件,並從發送到亞馬遜位置。喜歡的東西(未經測試):

// 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。

+0

錯誤是由HTTP引起的:base64字符串在發送到服務B時丟失了所有的+ char。方式是在基於64的字符串上調用urlencoded,在fopen/file_get_contents之前調用urldecode。 感謝所有 – Matte 2012-01-12 08:33:19