【问题标题】:how to write to database after javascript client side photo resize and uploadjavascript客户端照片调整大小和上传后如何写入数据库
【发布时间】:2015-06-17 19:50:28
【问题描述】:

我在网上找到了一个脚本,它可以调整图像客户端的大小,然后将图像上传到服务器。这工作正常,但我需要将图像名称写入 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>

上传调整大小的照片.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.
    }
?>

【问题讨论】:

    标签: javascript php jquery mysql upload


    【解决方案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)">
    

    祝你好运

    【讨论】:

    • 正是我正在寻找的感谢帮助。
    【解决方案2】:

    我在我的电脑上测试以下代码:

    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 + Files)

    【讨论】:

    • 文件确实正确上传到服务器,但我无法从上传 - 调整大小 - 照片中获取要执行的 sql 语句。
    • 是的,就是这样。现在工作100%。你知道我怎么能阻止上传图片以外的任何文件吗?感谢所有的帮助。
    猜你喜欢
    • 2014-11-29
    • 2010-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 2011-08-25
    相关资源
    最近更新 更多