将画布保存到图像 URL 并将其上传到 PHP 服务器
您可以将画布保存到这样的图像 URL(默认为 .png 格式):
canvas.toDataURL();
以下是如何在服务器上发布该 dataURL。
客户端:
// create a dataUrl from the canvas
var dataURL= canvas.toDataURL();
// use jQuery to POST the dataUrl to you php server
$.ajax({
type: "POST",
url: "upload.php",
data: {image: dataURL}
}).done(function( respond ) {
// Done...report success or failure
// You will get back the temp file name
// or "Unable to save this image."
console.log(respond);
});
服务器文件:upload.php
<?php
// make sure the image-data exists and is not empty
// xampp is particularly sensitive to empty image-data
if ( isset($_POST["image"]) && !empty($_POST["image"]) ) {
// get the dataURL
$dataURL = $_POST["image"];
// the dataURL has a prefix (mimetype+datatype)
// that we don't want, so strip that prefix off
$parts = explode(',', $dataURL);
$data = $parts[1];
// Decode base64 data, resulting in an image
$data = base64_decode($data);
// create a temporary unique file name
$file = UPLOAD_DIR . uniqid() . '.png';
// write the file to the upload directory
$success = file_put_contents($file, $data);
// return the temp file name (success)
// or return an error message just to frustrate the user (kidding!)
print $success ? $file : 'Unable to save this image.';
}
一些常见的陷阱(注意 xampp 对这些陷阱特别敏感):
- 确保 dataURL 不为空(您甚至可以检查这个客户端——未显示)。
- 确保您已在服务器上启用文件上传。
- 确保您在服务器上定义了足够的文件上传大小限制。
- 确保您已正确定义上传目录。
- 确保您在上传目录上正确设置了权限。
...并且,请耐心等待。您可能必须修补服务器才能运行。