キャンバスを画像 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 が空でないことを確認してください (このクライアント側を確認することもできます -- 表示されていません)。
- サーバーでファイルのアップロードが有効になっていることを確認してください。
- サーバーで適切なファイル アップロード サイズ制限を定義していることを確認してください。
- アップロード ディレクトリが正しく定義されていることを確認してください。
- アップロード ディレクトリに適切な権限が設定されていることを確認してください。
...そして、我慢してください。実行するには、サーバーをいじる必要がある場合があります。