我正在尝试将画布图像(使用html2canvas)上传到远程服务器,正在创建文件名,但大小为0字节。
$(function click1() {
$("#share").click(function() {
$("#load").show();
html2canvas($("#backdrop1"), {
onrendered: function(canvas) {
var data1 = canvas.toDataURL('image/png');
//display 64bit image
var image = new Image();
image.src = data1;
$.ajax({
url: 'uploading.php',
type: 'post',
data: {img_val: data1},
datatype: 'html',
success: function fbs_click1() {
$("#load").hide();
}
});
}
});
});
});
上面的Jquery代码生成了elemnt图像。
// Uploading.php
<?php
$imaged = $_POST['img_val'];
$filename = $_FILES[$imaged]['tmp_name'];
$handle = fopen($filename, "r");
$data = fread($handle,filesize($filename));
$POST_DATA = array(
'img_value' => base64_encode($data)
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://example.com/upload.php');
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $POST_DATA);
$response = curl_exec($curl);
curl_close ($curl);
?>
服务器端处理程序脚本即。 upload.php的
<?php
$img = $_REQUEST['img_value'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = 'test.png';
$success = file_put_contents($file, $data);
?>
请帮助我,我已经尝试了很多方法来保存,但我没有做到。
答案 0 :(得分:0)
以下是AJAX
的代码。您应该直接将从canvas
收到的图像数据传递到服务器。
在浏览器中,您会收到base64编码的图像内容
然后以纯文本格式将该内容传递到本地服务器。
希望这有帮助!
在客户端:
$(function click1() {
$("#share").click(function() {
$("#load").show();
html2canvas($("#backdrop1"), {
onrendered: function(canvas) {
var data1 = canvas.toDataURL("image/png");
//display 64bit image
var image = new Image();
image.src = data1;
$.ajax({
url: 'uploading.php',
type: 'post',
data: data1,
dataType: 'text',
contentType: "application/upload",
success: function fbs_click1() {
$("#load").hide();
}
});
}
});
});
});
在您的本地服务器上(upload.php):
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
$imageData = $GLOBALS['HTTP_RAW_POST_DATA'];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://example.com/upload.php" );
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($curl, CURLOPT_POST, 1 );
curl_setopt($curl, CURLOPT_POSTFIELDS, $imageData);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result=curl_exec ($curl);
echo $result;
curl_close ($curl);
?>
在您的移除服务器上(upload.php):
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
$filteredData=substr($imageData, strpos($imageData, ",")+1);
$unencodedData=base64_decode($filteredData);
$upload_dir = "PATH_TO_UPLOAD_DIRECTORY/";
$final_img = $upload_dir."my_upload_image.png";
if(file_put_contents($final_img, $unencodedData)) {
echo "SUCCESS";
}
else {
echo 'ERROR';
}
}
else
{
echo "ERROR";
}
exit;
答案 1 :(得分:0)
如果你想简单的话 1.删除upload.php 2.用下面的代码替换upload.php。
<html>
<head> ... </head>
<body>
<pre>{some: "data"}</pre>
<script>window.print()</script>
</body>
</html>