将画布图保存到服务器 [英] save canvas image to server
问题描述
我正在尝试将画布图像保存到服务器。我可以保存文件,但它总是0字节。我的代码有什么问题?
I'm trying to save the canvas image to the server. I can save the file, but it's always 0 bytes. What's wrong with my code?
<script>
function test(){
var canvas = document.getElementById("cvs");
var dataURL = canvas.toDataURL();
$.ajax({
type: "POST",
url: "upload.php",
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
});
}
</script>
php:
<?php
define('UPLOAD_DIR', 'uploads/');
$img = $_POST['img'];
$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 : 'Unable to save the file.';
?>
推荐答案
首先你必须确保在 c / c> dataURL $>之后> c / c $ c>
First you have to be sure that you have painted to the canvas after you defined the canvas
variable and before you created the dataURL
其次,看起来你在这个php行中寻找 img
:
Second, it seems like you are looking for img
in this php line:
$img = $_POST['img'];
但在您的javascript中,您将其定义为 imgBase64
in:
but in your javascript you are defining it as imgBase64
in:
data: {
imgBase64: dataURL
}
最后,您应该在 console.log(dataURL)
c $ c> dataURL 已创建,以确保其中有任何内容。
lastly you should be adding console.log(dataURL)
after the dataURL
has been created to be sure that there is anything in it.
这篇关于将画布图保存到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!