从浏览器发送图像到服务器 - 可能吗?

3

有一个图片库网站,用户可以通过javascript和HTML5画布操作图片。是否可能将处理后的图片发送回服务器以便使用PHP进行存储?


一个很好的解决方案是JqueryUI Sortable,你想要纯JavaScript吗? - Mihai Iorga
不,用jQuery没问题的,当然。谢谢,我会注意的。 - Csati
2个回答

4

您可以在这里找到有关此主题的完整文章。但这是简短的版本和源代码:

首先,您需要将画布二进制数据转换为Base64编码字符串,然后将其发送到服务器:

var image = canvas.toDataURL("image/png");

使用ajax调用发送此内容:

var ajax = new XMLHttpRequest();
ajax.open("POST",'save.php', false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(image);

最后,PHP脚本save.php应该是这样的:
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
    // Get the data
    $imageData=$GLOBALS['HTTP_RAW_POST_DATA'];

    // Remove the headers (data:,) part. 
    // A real application should use them according to needs such as to check image type
    $filteredData=substr($imageData, strpos($imageData, ",")+1);

    // Need to decode before saving since the data we received is already base64 encoded
    $unencodedData=base64_decode($filteredData);

    //echo "unencodedData".$unencodedData;

    // Save file.  This example uses a hard coded filename for testing,
    // but a real application can specify filename in POST variable
    $fp = fopen( 'test.png', 'wb' );
    fwrite( $fp, $unencodedData);
    fclose( $fp );
}
?>

这个 PHP 脚本会解析原始的 post 数据,并将其从 base 64 转换为二进制数据,最终保存为文件。如需了解 Base 64 的更多信息,请查看维基百科文章。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接