javascript客户端照片调整大小并上传后如何写入数据库

时间:2015-04-12 12:27:49

标签: javascript php jquery mysql upload

我在网上找到了一个脚本,它调整了图像客户端的大小,然后将图像上传到服务器。这工作正常但我需要的是将图像名称写入mysql数据库。我知道该怎么做,但它不起作用,我认为它与脚本运行客户端这一事实有关。

任何人都可以查看以下内容并查看将mysql语句放在何处。或者,如果有更好的方式完成它。

上传-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>

上传调整大小-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 个答案:

答案 0 :(得分:1)

我在计算机上测试以下代码:

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();        
}

检查您的文件夹权限,请参阅以下图像(Mysql +文件)

enter image description here enter image description here

答案 1 :(得分:1)

此功能检查所有输入[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;
}

你应该在:

中调用该函数
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;
 }

并在表单中将表单作为参数传递:

<form enctype="multipart/form-data" method="post" onsubmit="return uploadphoto(this)">
祝你好运