1
我的问题与this thread非常相似。我正在创建一个画布元素,添加一个或多个img元素,并将每个img依次发布到服务器上的一个php脚本,然后保存生成的文件。这是对图像的基本拖放操作,非常类似于Facebook或G +上的操作。我有一切正常工作,除了上传和保存产生的文件都是空的 - 或者说,他们每个2kb,只显示黑色。base64 image post to php results in empty file
下面的代码的相关部分: HTML:
<form method="post" action="upload.php" id="formUpload">
<div id="op">
<label class="lbl">Drop images here to add them,<br>or click an image to see it enlarged</label>
<span style='display:inline-block'>
<input type="file" name="files[]" id='file' class="fileUpload" onchange="startRead()" multiple><br>
<input type='submit' name='submit' value='+' class="fileUpload">
</span>
</div>
</form>
(不与CSS困扰,因为它不是有密切关系这一点)
的JavaScript/jQuery的:
function addImg(imgSrc) {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 5, 5);
};
imageObj.className = "imgThumbnail";
imageObj.style.width = 140 + "px";
imageObj.style.height = 140 + "px";
imageObj.src = imgSrc.currentTarget.result;
var dataURL = canvas.toDataURL();
$.ajax({
type: "POST",
url: "upload.php",
data: {
imgBase64: dataURL
}
}).done(function(data) {
var fileName = data;
if (fileName.substring(1,1) !== "!") {
document.getElementById('op').insertBefore(imageObj);
$("#op").on('click', 'img', imgEnlarge);
$.get($("#path").val() + "/includes/addImage.php", {
imageType: $("#imageType").val(),
idParentObject: $("#idParentObject").val(),
url: fileName
});
} else {
alert("Error in upload processs. Could not save " + data.substring(2, data.length-1) + ".");
imageObj.attr("src", "../images/missing.png");
}
});
}
PHP :
define('UPLOAD_DIR', '../images/');
$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 : '!$file';
任何帮助搞清楚我失踪将不胜感激。正确的答案将会更加赞赏。