您好,我需要获取要与 Canvas 图像一起提交的表单数据。然后使用该表单数据来命名保存在服务器上的文件。我刚刚开始掌握 PHP,所以任何帮助都会很棒。
这是我的工作示例,它将把相同的命名文件保存到服务器。
HTML
<form action="name.php" method="post">
Name: <input type="text" name="fname">
Age: <input type="text" name="age">
<input type="button" onclick="saveImage();formSubmit();" value="Submit form">
</form>
JS
function saveImage(){
var xmlhttp;
xmlhttp=((window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP"));
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//do something with the response
}
}
xmlhttp.open("POST","upload.php",true);
var oldCanvas = document.getElementById('colors_sketch').toDataURL("image/png");
var img = new Image();
img.src = oldCanvas;
xmlhttp.setRequestHeader("Content-type", "application/upload")
xmlhttp.send(oldCanvas);
}
PHP
$data = file_get_contents('php://input');
$canvasImg = imagecreatefrompng($data);
$width = imagesx($canvasImg);
$height = imagesy($canvasImg);
$outImg = imagecreatetruecolor($width, $height);
$color = imagecolorallocatealpha($outImg, 255, 255, 255, 127);
imagefill($outImg, 0, 0, $color);
imagecopy($outImg, $canvasImg, 0, 0, 0, 0, $width, $height);
imagepng($outImg, 'test.png');
最佳答案
以下是将表单和图像发送到 upload.php 的步骤
首先创建一个要发送的数据包,其中包括序列化图像和表单。这里我使用jquery来序列化你的表单(或者不用jquery自己序列化)。
// serialize and concatenate both form and canvas image
var package=$("form").serialize() + "&imageDataURL="+canvas.toDataURL();
然后使用 AJAX 将其 POST 到您的 PHP 服务器:
// ajax it
postImagePlusForm();
function postImagePlusForm(){
$.ajax({
type: "POST",
url: "upload.php",
data: package,
success: function(value) {
// ...we have success!
}
});
}
最后捕获它并在 php 中处理它:
<?php
if ( isset($_POST["imageDataURL"]) && !empty($_POST["imageDataURL"]) ) {
// create $dataURL
$dataURL = $_POST["imageDataURL"];
// Extract base64 data
// we have an unneeded header, zap it
$parts = explode(',', $dataURL);
$data = $parts[1];
// Decode
$data = base64_decode($data);
// Save
$fp = fopen('newImage.png', 'w');
fwrite($fp, $data);
fclose($fp);
}
if ( isset($_POST["formData"]) && !empty($_POST["formData"]) ) {
$formData = $_POST['formData'];
foreach ($formValue as $x) {
// do whatever you need to do with each form value ($x)
}
}
关于php - 将 Canvas 图像和表单数据发送到服务器以命名为 png,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16148371/