javascript 将画布图像保存到服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27213366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
save canvas image to server
提问by user3080392
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?
我正在尝试将画布图像保存到服务器。我可以保存文件,但它总是 0 字节。我的代码有什么问题?
<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:
<?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.';
?>
采纳答案by NatureShade
First you have to be sure that you have painted to the canvas afteryou defined the canvas
variable and beforeyou created the dataURL
首先,您必须确保在定义canvas
变量之后和创建变量之前已经绘制到画布上dataURL
Second, it seems like you are looking for img
in this php line:
其次,您似乎正在img
此 php 行中查找:
$img = $_POST['img'];
but in your javascript you are defining it as imgBase64
in:
但是在您的 javascript 中,您将其定义为imgBase64
:
data: {
imgBase64: dataURL
}
lastly you should be adding console.log(dataURL)
after the dataURL
has been created to be sure that there is anything in it.
最后,您应该在创建console.log(dataURL)
之后添加dataURL
,以确保其中有任何内容。