CodeIgniter Forums

Full Version: Optional file upload
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]PermanaJ[/eluser]
I have a form where there are two input field, and a file upload field. How can I make this file upload field optional ? user can provide file or not because when I use file upload class, It always return "You did not select a file to upload."

First, I try this code :
Code:
if( isset ($_FILES['photo']) ){
    if( !$this->upload->do_upload('photo')){
        $upload_error = $this->upload->display_errors();
    }else{
        $photo = $this->upload->data();
    }
}

It doesn't work, return same error message.

El Forum

[eluser]Thorpe Obazee[/eluser]
Code:
if($_FILES AND isset($_FILES['field_name']['name'])) ){
    if( !$this->upload->do_upload('photo')){
        $upload_error = $this->upload->display_errors();
    }else{
        $photo = $this->upload->data();
    }
}

Please try this.

omg! 888 posts. Feng shui..

El Forum

[eluser]PermanaJ[/eluser]
thanks bargainph, but Its not working ..

El Forum

[eluser]Thorpe Obazee[/eluser]
[quote author="PermanaJ" date="1245336154"]thanks bargainph, but Its not working ..[/quote]

What do you mean by it's not working?

El Forum

[eluser]PermanaJ[/eluser]
I mean i still got the “You did not select a file to upload.” message .. (sorry my english is not so good)

El Forum

[eluser]Thorpe Obazee[/eluser]
Sorry.

What happens when you choose a file to upload?
What happens when you do not choose a file to upload?

El Forum

[eluser]PermanaJ[/eluser]
both return "You did not select a file to upload."

Now I'm wondering if the mistake is on my script. But everything fine when I remove the code and file upload file from the form .

El Forum

[eluser]PermanaJ[/eluser]
whoops ... I handle which one from $upload_error or $photo exist .. if $upload_error, then show error and stop processing form .. I just need to continue processing form even there are $upload_error

El Forum

[eluser]ok3x[/eluser]
Make sure your form comes with multipart/form-data attribute.

El Forum

[eluser]gtech[/eluser]
[quote author="PermanaJ" date="1245342070"]whoops ... I handle which one from $upload_error or $photo exist .. if $upload_error, then show error and stop processing form .. I just need to continue processing form even there are $upload_error[/quote]

your right but your code suggests that it should not pass the first if statement

have you tried

Code:
if ($_FILES['photo']['name']!="") {
    if( !$this->upload->do_upload('photo')){
        $upload_error = $this->upload->display_errors();
    }else{
        $photo = $this->upload->data();
    }
};

that way you can keep the display errors in if the upload fails when there is a file to upload.