【发布时间】:2014-12-16 16:21:21
【问题描述】:
正在将画布转换为图像并在用户提交表单时将其上传到服务器。 图片正确发布,但在服务器中显示为空。
这是我的代码,(我正在使用 phonegap)
.drawImage ()在 main.js 中.. 但canvas..toDataURL在 html 中的脚本中
<script>
function insert()
{
var img = document.getElementById("myCanvas")[0].toDataURL("image/jpeg");
$.ajax({
type: "POST",
url: "http://*******************/create.php?title="+ ($("#myTitle").val())+"&description="
+$("#myDesc").val()+"&price="+$("#myPrice").val(),
data: {img: img},
success: function(data)
{
alert("inserted");
}});
</script>
php
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
有什么想法吗?
编辑!!!
终于要上传了!!!
感谢 Jack Franzen 的建议。 我已将 php 代码更改为
$img = $_POST['img'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = uniqid() . '.jpg';
$success = file_put_contents($file, $data);
它就像魅力一样! :)
【问题讨论】:
-
如您所见,JavaScript 部分很好。对于 PHP 部分,您可以使用对 PHP-FileUpload 的调用来替换您的实现,其中包括
DataUriUpload,记录在案的 here。它负责一切,即接受一种或多种 MIME 类型并映射到扩展名、选择文件名、验证大小。
标签: javascript php html canvas