简体   繁体   English

如何在服务器上捕获图像并显示在html页面上?

[英]How do I grab an image on a server and display on a html page?

I am trying to get a canvas that I have saved to pop up in my html window. 我正在尝试获取已保存的画布,以在HTML窗口中弹出。 Not sure how to grab it on the html page because the save generates a random name for the image. 不确定如何在html页面上获取它,因为保存会为图像生成一个随机名称。

The Save code: 保存代码:

function saveImage() {
cursor.visible = false; stage.update();
var canvasData = testCanvas.toDataURL("image/png");
window.open(("../popup.html"));
var xmlHttpReq = false;       
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
cursor.visible = true; stage.update();
}

else if (window.ActiveXObject) {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
alert (nameOfFile);
ajax.open('POST', 'testSave.php', false);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.onreadystatechange = function() {
console.log(ajax.responseText);
}
ajax.send("imgData="+canvasData);
}

The PHP: PHP:

<?php
// requires php5
define('UPLOAD_DIR', 'images/');
$img = $_POST['img'];
$img = str_replace('data:images/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.';
?>

The popup.html popup.html

<div><strong>Image to display below</strong></div>

<script>
window.onload = function() {
document.getElementById('imgData="+canvasData').src = localStorage.getItem('images/');
};
</script>

Your PHP is already returning the $file that was created on the server. 您的PHP已经返回了在服务器上创建的$ file。

So, you could POST with jQuery and add a callback that receives that unique filename created on the server (or the error message if an error occurred). 因此,您可以使用jQuery POST并添加一个回调,以接收在服务器上创建的唯一文件名(如果发生错误,则返回错误消息)。

// create a dataUrl from the canvas
var dataURL= canvas.toDataURL();

// post the dataUrl to php
$.ajax({
  type: "POST",
  url: "upload.php",
  data: {image: dataURL}
}).done(function( respond ) {
  // you will get back the temp file name
  // or "Unable to save this image."
  console.log(respond);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM