当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Javascript validate file input name

问题描述:

I currently having a problem to validate the file name that user upload into the file input. I already had the validation on file extension, but when user trying to upload a file name example 1.hello.jpg, for my JavaScript validation code it was look okay as it was jpg extension. But in my PHP part my validation for the file extension does not recognize it as I'm using explode function to validate the file extension.

Is there anyway to validate the special character of the file in client side before submitted to my server side? Thanks

Here are my validation on client side:

 <script type='text/javascript'>

function checkDisabled(yourSubmitButton){

//No 1 file input validation

var res_field = document.getElementById('uploaded_file').value;

var extension = res_field.substr(res_field.lastIndexOf('.') + 1).toLowerCase();

var allowedExtensions = ['jpg','JPG','bmp','BMP','png','PNG','jpeg','JPEG'];

if(document.getElementById('bannerName').value.length !=0){

//File input extension validation

if (res_field.length > 0)

{

if (allowedExtensions.indexOf(extension) !== -1)

{

yourSubmitButton.disabled = false;

return;

}

}

}

// If we have made it here, disable it

yourSubmitButton.disabled = true;

};

</script>

Here are my php code for validate the extension:

$valid_formats = array("jpg", "JPEG","png","PNG","bmp","BMP",'JPG','jpeg');

if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")

{

$name = $_FILES['uploaded_file']['name'];

$size = $_FILES['uploaded_file']['size'];

$bName = $_POST['bannerName'];

$bDescription = $_POST['bannerDescription'];

$bK = $_POST['bannerK'];

$bKe = $_POST['bannerKe'];

$bS= $_POST['bannerS'];

if(strlen($name))

{

list($txt, $ext) = explode(".", $name);

if(in_array($ext,$valid_formats))

{

...........

}

}

网友答案:

In your PHP use PATHINFO_EXTENSION to get the file extension :

$ext = pathinfo($name, PATHINFO_EXTENSION);

For more info , check Here.

网友答案:

Try access the below value

$_FILES["uploaded_file"]["type"] 

and validate in server side.

网友答案:

I had solve it by using split function on javascript.

Here is my code:

//Check for dot that is not more than 1
            var checkStr = 0;
            var str = document.getElementById('uploaded_file').value;
            var res = str.split(".");

            for(var i = 0 ; i <= res.length;i++){
                checkStr++;
            }

            if(checkStr>3){

                alert(str+' invalid filename detected. \n\n Please rename your file.');
                return false;
            }

For those beginner like me can refer to that, as i'm trying to split the filename that browser into the file input. If the array after split function is more than 3 then prompt out error.

Example :

  1. -1.hello.jpg (Error)
  2. -1_hello.jpg (Success)

Thanks for all the help. Much Appreciate

分享给朋友:
您可能感兴趣的文章:
随机阅读: