Skip to content Skip to sidebar Skip to footer

Limit File Name Before Uploading To Server In PHP, HTML And Javascript

I have searched in the previous question, but most of the answer is only trim the file name. But for me, I would like to display an alert message to user when their filename length

Solution 1:

You can use the File.name web API for this.

To accomplish this, you'll want to add an onchange event to your input field, and then create a javascript function to capture the event. In that function, you'll access the selected file's name and perform the validation. For example:

<input
    type="file" name="userfile" id="userfile"
    accept="image/jpeg, application/pdf"
    onchange="validateFile(this)"
/>

<script>
    function validateFile(fileInput) {
        var files = fileInput.files;
        if (files.length === 0) {
            return;
        }

        var fileName = files[0].name;
        if (fileName.length > 15) {
            alert('File input name to long.');
        }
    }
</script>

It's worth noting, for security reasons, you should not store the file with the name the user supplies. It's safe to store it in a database and used as a label when showing users (pending you sanitize it first) - but the file path you save on your server should be 100% controlled by you.


Post a Comment for "Limit File Name Before Uploading To Server In PHP, HTML And Javascript"