开发者

php javascript form validation for upload file <input>

开发者 https://www.devze.com 2023-01-15 07:17 出处:网络
want to get a 开发者_如何学Govalidation script to validate the file upload box onsubmit. check the extension of the file and validate accordingly to the extension of file loadedCheck here: http://jsf

want to get a 开发者_如何学Govalidation script to validate the file upload box onsubmit.

check the extension of the file and validate accordingly to the extension of file loaded


Check here: http://jsfiddle.net/uh2Gn/

HTML:

<form method="post" enctype="" onsubmit="return validate()">
    <input type="file" id="file" />
    <input type="submit" />
</form>

JavaScript:

function validate() {
    var filename=document.getElementById('file').value;
    var extension=filename.substr(filename.lastIndexOf('.')+1).toLowerCase();
    //alert(extension);
    if(extension=='jpg' || extension=='gif') {
        return true;
    } else {
        alert('Not Allowed Extension!');
        return false;
    }
}

Keep in mind that this is only for user convenience, that he doesn't go theu a long submit process to get an error at the server, cuz for sure you must implement a check at server-side.


If you don't mind jquery, then you can use the validation plugin, which is available here. A brief introduction and small demo is available here.


I use the following in my php script for validation.

$status_file = validate_and_upload("project_file");


function validate_and_upload($input_tag_name)
{
    $allowedExts = array("gif", "jpeg", "jpg", "png", "ppt", "doc", "pdf", "xls", "xlxs", "txt", "docx");
    $filename = $_FILES[$input_tag_name]['name'];
    if ( !$filename )
      return 0;
    $extension = pathinfo($filename, PATHINFO_EXTENSION);

    if ( ($_FILES[$input_tag_name]["size"] < 33554432) && in_array($extension, $allowedExts) ) // 33554432 is 32.00 MB
        {
            if ($_FILES[$input_tag_name]["error"] > 0) 
            {
                echo "Return Code: " . $_FILES[$input_tag_name]["error"] . "<br>";
                return -1;
            } 
            else 
            {
                if (file_exists("/sites/default/files/private/" . $_FILES[$input_tag_name]["name"])) 
                {
                    echo $_FILES[$input_tag_name]["name"] . " already exists. ";
                    return 2;
                } 
                else 
                {
                    $hard_disk_upload_directory = "C://xampp/htdocs/mywebsite/sites/default/files/private/";
                    if (move_uploaded_file($_FILES[$input_tag_name]["tmp_name"], $hard_disk_upload_directory . $_FILES[$input_tag_name]["name"]))
                        return 1;
                    else
                        return -1;
                }
            }
        } 
        else 
        {
            echo "<script>alert('Invalid file'); window.location.href='http://mywebsite/home';</script>";
            return -1;
        } 
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消