I have found a script online which resizes an image client side and then uploads the image to server. This works fine but what I need is to write the image name to mysql database. I know how to do it, but its not working and I think it has something to do with the fact that the script runs client side.
我在网上找到了一个脚本,它调整了图像客户端的大小,然后将图像上传到服务器。这工作正常但我需要的是将图像名称写入mysql数据库。我知道该怎么做,但它不起作用,我认为它与脚本运行客户端这一事实有关。
Can anyone look at the following and see where to put the mysql statement. Or if there is a better way of doing it altogether.
任何人都可以看看以下内容,看看放置mysql语句的位置。或者,如果有更好的方式完成它。
upload-form.php
<script>
function uploadphoto()
{
if (window.File && window.FileReader && window.FileList && window.Blob)
{
var files = document.getElementById('filesToUpload').files;
for(var i = 0; i < files.length; i++)
{
resizeAndUpload(files[i]);
}
}
else
{
alert('The File APIs are not fully supported in this browser.');
}
}
function resizeAndUpload(file)
{
var reader = new FileReader();
reader.onloadend = function()
{
var tempImg = new Image();
tempImg.src = reader.result;
tempImg.onload = function()
{
var MAX_WIDTH = 695;
var MAX_HEIGHT = 470;
var tempW = tempImg.width;
var tempH = tempImg.height;
if (tempW > tempH)
{
if (tempW > MAX_WIDTH)
{
tempH *= MAX_WIDTH / tempW;
tempW = MAX_WIDTH;
}
}
else
{
if (tempH > MAX_HEIGHT)
{
tempW *= MAX_HEIGHT / tempH;
tempH = MAX_HEIGHT;
}
}
var canvas = document.createElement('canvas');
canvas.width = tempW;
canvas.height = tempH;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, tempW, tempH);
var dataURL = canvas.toDataURL("image/jpeg");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(ev)
{
document.getElementById('filesInfo').innerHTML = 'Done!';
};
xhr.open('POST', 'upload-resized-photo.php', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var data = 'image=' + dataURL;
xhr.send(data);
}
}
reader.readAsDataURL(file);
}
</script>
<form enctype="multipart/form-data" method="post" onsubmit="uploadphoto()">
<div class="row">
<label for="fileToUpload">Select Files to Upload</label><br />
<input type="file" name="filesToUpload[]" id="filesToUpload" multiple="multiple" />
<output id="filesInfo"></output>
</div>
<div class="row">
<input type="submit" value="Upload" />
</div>
</form>
upload-resized-photo.php
<?php
if ($_POST)
{
define('UPLOAD_DIR', 'uploads/');
$img = $_POST['image'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.jpg';
$success = file_put_contents($file, $data);
// I did have the mysql insert here but it didnt even execute. Think it is due to xhr.open post method.
}
?>
2 个解决方案
#1
1
I test the following code on my computer:
我在计算机上测试以下代码:
if ($_POST)
{
define('UPLOAD_DIR', 'uploads/');
$img = $_POST['image'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.jpg';
$success = file_put_contents($file, $data);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO images (image_name)
VALUES ('{$file}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
check your folder permissions, see the following images (Mysql + Files)
检查您的文件夹权限,请参阅以下图像(Mysql + Files)
#2
1
This function check all input[type=file]
此功能检查所有输入[type = file]
var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
function Validate(oForm) {
var arrInputs = oForm.getElementsByTagName("input");
for (var i = 0; i < arrInputs.length; i++) {
var oInput = arrInputs[i];
if (oInput.type == "file") {
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
return false;
}
}
}
}
return true;
}
you should call that function in:
你应该在以下方面调用该函数:
function uploadphoto(oForm)
{
if(!Validate(oForm)){
return false;
}
if (window.File && window.FileReader && window.FileList && window.Blob)
{
var files = document.getElementById('filesToUpload').files;
for(var i = 0; i < files.length; i++)
{
resizeAndUpload(files[i]);
}
}
else
{
alert('The File APIs are not fully supported in this browser.');
}
return false;
}
and in your form pass the form as parameter:
并在您的表单中传递表单作为参数:
<form enctype="multipart/form-data" method="post" onsubmit="return uploadphoto(this)">
Good luck
#1
1
I test the following code on my computer:
我在计算机上测试以下代码:
if ($_POST)
{
define('UPLOAD_DIR', 'uploads/');
$img = $_POST['image'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.jpg';
$success = file_put_contents($file, $data);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO images (image_name)
VALUES ('{$file}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
check your folder permissions, see the following images (Mysql + Files)
检查您的文件夹权限,请参阅以下图像(Mysql + Files)
#2
1
This function check all input[type=file]
此功能检查所有输入[type = file]
var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
function Validate(oForm) {
var arrInputs = oForm.getElementsByTagName("input");
for (var i = 0; i < arrInputs.length; i++) {
var oInput = arrInputs[i];
if (oInput.type == "file") {
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
return false;
}
}
}
}
return true;
}
you should call that function in:
你应该在以下方面调用该函数:
function uploadphoto(oForm)
{
if(!Validate(oForm)){
return false;
}
if (window.File && window.FileReader && window.FileList && window.Blob)
{
var files = document.getElementById('filesToUpload').files;
for(var i = 0; i < files.length; i++)
{
resizeAndUpload(files[i]);
}
}
else
{
alert('The File APIs are not fully supported in this browser.');
}
return false;
}
and in your form pass the form as parameter:
并在您的表单中传递表单作为参数:
<form enctype="multipart/form-data" method="post" onsubmit="return uploadphoto(this)">
Good luck