douxia1988 2014-07-06 08:37
浏览 33
已采纳

为什么PHP不能通过AJAX成功创建PNG图像?

I made an simple application how the users can edit canvas and send Canvas Base 64 data via ajax with PHP to create PNG images in this folder, the problem is it won't create PNG Images.

App web link; using Chrome, press F12 for inspection, check "Network" tab with XHR category, when you click "Upload" button, it will appear "canvasupload.php" http://www.powerupware.com/canva/

This PHP code:

<?php

    $name = $_POST['name']; //optional variable

    define ('UPLOAD_DIR', 'userCanvas/'); //folder to save image

    $img =  $_POST['CanvasPic']; //get from canvas base64 by user who posts via AJAX

    //base 64 string to convert image file properly
    $img = str_replace('data:image/png;base64,' '', $img);
    $img = str_replace(' ', '+', $img);


    //create PNG file
    $data = base64_decode($img);
    $file = UPLOAD_DIR . uniqid() . '.png'; //outputs as image file in server with unique ID.

    $success = file_put_contents ($file, $data);

    print $success ? $file : 'Could not save the file!';

?>

After uploading this canvas, I got 200 OK with POST method, When I go to FTP, I open userCanvas folder and found no new png image files.

  • 写回答

1条回答 默认 最新

  • douyou2234 2014-07-06 09:37
    关注

    I've figured out, for unknown reason, I created another code like this:

    <?php
    
    $img = $_POST['CanvasPic'];
    define('UPLOAD_DIR', 'userCanvas/');
    
    
    $img = str_replace('data:image/png;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    
    $data = base64_decode($img);
    $file = UPLOAD_DIR . uniqid() . '.png';
    
    $success = file_put_contents($file, $data);
    
    print $success ? $file : 'Could not save the file!';
    
    ?>
    

    It worked, I can see new PNG files in this folder, I don't know why....

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?