koool
koool

Reputation: 15517

How to make sure a file is selected before uploading

Hi I am using codeigniter for file uploading and I am using this code

echo form_open_multipart('controller_a');
echo form_upload('userfile');
echo form_submit('Upload','upload');
echo form_close();

I store the pointer to the uploaded file in the database, My question is how do I make sure that the user has selected a file before clicking on upload button because as of now the code submits even if the user clicks directly on upload without selecting a file

Upvotes: 1

Views: 554

Answers (4)

MÇT
MÇT

Reputation: 1143

Along with client side verification, you should use server side verification, too. Currently, CodeIgniter does not provide a function, so one can use native PHP function is_uploaded_file:

if (is_uploaded_file($_FILES['myfile']['tmp_name']))
{
    $this->load->library('upload');

    $this->upload->do_upload('myfile');
}

Upvotes: 1

tylerpenney
tylerpenney

Reputation: 239

Your best bet is to use a jQuery plugin like the following:

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

This will allow you to select what input values will need to be selected, and customize a message to inform the user what field(s) they are missing.

Upvotes: 0

Vamsi Krishna B
Vamsi Krishna B

Reputation: 11490

use JS

very basic code, but it works.

<script type="text/javascript">

<!--

function validate_form ( )
{
    valid = true;

        if ( document.upload_form.something.value == "" )
        {
                alert ( "Please select a file before clicking upload ! " );
                valid = false;
        }

        return valid;
}

//-->

</script>

and use onsubmit even in the form

onSubmit="return validate_form ( );"

when a user click on upload button without selecting any file, it will alert the user .

Upvotes: 0

cwallenpoole
cwallenpoole

Reputation: 81988

You can't, not in CodeIgniter at least. You'll need to have JS overwrite the onsubmit property of the form and then test the userfile input's value.

Upvotes: 0

Related Questions