我有一个注册页面,其中包含使用HTML5中名为GetUserMedia()的新API的上传个人资料图片部分。此API激活我的网络摄像头并捕获配置文件图像的图像。当我捕获图像并尝试使用我的html表单提交它时,它会上传一个大小为0KB的图像(因此没有图像只上传一个空白的.png容器)。
Javascript用于激活相机并将imgBase64以.png格式上传到php验证表格
// Webcam Detection
// Put event listeners into place
window.addEventListener("DOMContentLoaded", function () {
// Grab elements, create settings, etc.
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
videoObj = { "video": true },
errBack = function (error) {
console.log("Video capture error: ", error.code);
};
// Put video listeners into place
if (navigator.getUserMedia) { // Standard
navigator.getUserMedia(videoObj, function (stream) {
video.src = stream;
video.play();
}, errBack);
} else if (navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(videoObj, function (stream) {
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
} else if (navigator.mozGetUserMedia) { // WebKit-prefixed
navigator.mozGetUserMedia(videoObj, function (stream) {
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
}
// Trigger photo take
document.getElementById("snap").addEventListener("click", function () {
context.drawImage(video, 0, 0, 200, 150);
// Littel effects
$('#snap').show();
// $('#upload').show();
});
// Upload image to sever
document.getElementById("upload").addEventListener("click", function () {
var dataUrl = canvas.toDataURL();
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['REQUEST_URI']; ?>",
data: {
imgBase64: dataUrl
}
})
});
}, false);
用于验证的PHP表单,我使用Safari和IE的后备,因为他们还不支持GetUserMedia。
<?php
if(isset($_POST['submit']))
{
//retrieve our data from POST
$rawData = $_POST['imgBase64'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username_post = $_POST['username'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
if($pass1 != $pass2){
echo '<link rel="stylesheet" type="text/css" href="css/structure.css">';
echo '<div class="alert">Passwords do not match!</div>';
die();
}
$encrypted_mypassword = sha1($pass1);
// Upload Image From Camera Using GetUserMedia API
if(!empty($_POST['imgBase64']){
$filteredData = explode(',', $rawData);
$unencoded = base64_decode($filteredData[1]);
$randomName = rand(0, 99999);;
//Create the image
$fp = fopen("/var/www/Directory1/Directory2/$randomName.png", 'w');
fwrite($fp, $unencoded);
fclose($fp);
}
//Fallback for Safari and IE
$uploaddir = "/var/www/directory1/directory2/";
$uploadfile = $uploaddir . basename($_FILES["submit"]["name"]);
echo "<p>";
if (move_uploaded_file($_FILES["submit"]["tmp_name"], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
?>
HTML表单
<html>
<head>
<title>Secure Customer Login</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="stylesheet" type="text/css" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/structure_register.css">
<link href='https://fonts.googleapis.com/css?family=Nothing+You+Could+Do' rel='stylesheet' type='text/css'>
<script>document.createElement('footer');</script>
<script type="application/javascript" src="scripts/webcam.js" charset="utf-8"></script>
</head>
<body>
<div class="img">
<img src="images/logo.png" />
</div>
<form class="box login" style="max-width:334px;" name="register" action="<?php echo $_SERVER['REQUEST_URI']; ?>" enctype="multipart/form-data" method="post">
<fieldset class="boxBody">
<label>First Name</label>
<input type="text" name="firstname" maxlength="50" tabindex="1" placeholder="First Name" required />
<label>Last Name</label>
<input type="text" name="lastname" maxlength="50" tabindex="2" placeholder="Last Name" required />
<label>Username</label>
<input type="email" name="username" maxlength="50" tabindex="3" placeholder="Email" required/>
<label>Password</label>
<input type="password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{6,}" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Password must contain at least 6 characters, including UPPER and lowercase and numbers' : ''); if(this.checkValidity()) form.pass2.pattern = t$
<label>Repeat Password</label>
<input type="password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{6,}" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Please enter the same Password as above' : '');" placeholder="Repeat Password" name="pass2" tabindex="5" />
<?php
$browser = get_browser(null, true);
if ($browser["browser"] == "Chrome" || $browser["browser"] == "Firefox"){
echo '<label>User Profile Image</label><br>';
echo '<center><video id="video" width="300" height="200" autoplay></video></center><br>';
echo '<button id="snap">Capture</button><br><br>';
echo '<center><canvas id="canvas" width="200" height="150"></canvas></center>';
}
if ($browser["browser"] == "Safari" || $browser["browser"] == "IE") {
echo '<label>Import Profile Picture</label>';
echo '<input type="file" capture="camera" accept="image/*" id="submit" name="submit">';
}
?>
</fieldset>
<footer>
<center><input type="submit" name="submit" value="Register" class="btnLogin" /></center>
</footer>
</form>
</html>
我怀疑问题在于此时的javascript:
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['REQUEST_URI']; ?>",
data: {
imgBase64: dataUrl
这是我尝试将POST数据发送到php脚本的时候。提交表单时图像为0KB,这使我认为javascript不会将任何数据发送到php表单。