EllisLab text mark
Advanced Search
1 of 2
1
   
Form Data and File Upload
Posted: 30 November 2009 06:48 PM   [ Ignore ]
Avatar
Joined: 2008-09-07
119 posts

Does anyone have any recommendations on how to use the file upload class with form data when the file upload is not required?

I have a form with 6 form fields. Five are text and one is the file field.

I don’t want the the file field to be required. However, when I submit the form I get the error stating that there is no file to upload all by itself and no other form errors show.

Any suggestions?

 Signature 

Branson Web Design
Handmade Fashion Jewelry

 
Posted: 30 November 2009 09:28 PM   [ Ignore ]   [ # 1 ]   [ Rating: 0 ]
Avatar
Joined: 2008-03-26
163 posts

Could you post your code? I have some ideas, but I’d need to see how you’re doing it to test them.

jeremy

 Signature 

Jeremy Gimbel, web nerd and developer and ExpressionEngine enthusiast, Mastermind at Conflux Group, Inc.
twitter: @dreadfullyposh
web: http://confluxgroup.com
blog: http://dreadfullyposh.com

 
Posted: 30 November 2009 11:57 PM   [ Ignore ]   [ # 2 ]   [ Rating: 0 ]
Avatar
Joined: 2008-09-07
119 posts

controller function:

function add(){
    $this
->load->library('form_validation');
    
$this->load->helper('form');
    
$this->form_validation->set_error_delimiters('<div class="errorDiv">','</div>');
    
$this->form_validation->set_rules('news_title','Title','required|trim|max_length[63]|xss_clean');
    
$this->form_validation->set_rules('active','Active','required|trim|exact_length[1]|xss_clean');
    
$this->form_validation->set_rules('news_desc','Description','required|trim|max_length[255]|xss_clean');
    
$this->form_validation->set_rules('news_body','Body','required|trim|max_length[65000]|xss_clean');
    
$this->form_validation->set_rules('news_month','Month','required|trim|xss_clean');
    
$this->form_validation->set_rules('news_date','Date','required|trim|xss_clean');
    
$this->form_validation->set_rules('news_year','Year','required|trim|xss_clean');        
    if(
$this->form_validation->run()==FALSE){            
        $data[
'token'md5(uniqid(mt_rand(),true));
        
$this->session->set_userdata('token',$data['token']);
        
$data['title'$this->Page->title;
        
$data['desc'$this->Page->desc;
        
$data['kw'$this->Page->kw;
        
$data['body'$this->Page->body;
        
$data['menu'$this->Page->setMenu();
        
$data['subMenu'$this->Page->childPages;
        
$data['newsList'$this->MNews->getNewsByUserID($this->session->userdata('user_id'));
        
$data['contentView''admin/news_add';
        
$this->load->view('template',$data);
    
}else{            
//        Process the submitted form here .......
        
if(!(
            (
$this->session->userdata('token')==$this->input->post('token')) && 
            (
$this->input->post('submit')=='Save News Item'
        
))){
            $this
->session->set_flashdata('fail_string','OOPS! There was problem with the form you submitted.');
            
redirect('main/logout','refresh');
        
}
        $data[
'token'$this->input->post('token');
        
$config['upload_path']='./photos/news/';
        
$config['allowed_types']='gif|jpg|png';
        
$config['max_size']='2000';
        
$config['max_width']='5000';
        
$config['max_height']='5000';
        
$config['remove_spaces']=TRUE;
        
$this->load->library('upload'$config);        
        if (!(
$this->upload->do_upload())){
            $this
->session->set_flashdata('fail_string',$this->upload->display_errors());
            
redirect('admin/news/add');
        
}else{
            $data 
= array('upload_data'=>$this->upload->data());
            
rename($config['upload_path'].$data['upload_data']['file_name'],$ni=$config['upload_path'].md5(date('U').$_SERVER['REMOTE_ADDR']).".jpg");             
            
$config['image_library']='gd2';
            
$config['source_image']=$ni;
            
$config['create_thumb']=FALSE;
            
$config['maintain_ratio']=TRUE;
            
$config['width']=350;
            
$config['height']=350;
            
$this->load->library('image_lib'$config);
            
$this->image_lib->resize();
            
$data['title']=$this->Page->title;
            
$data['desc']=$this->Page->desc;
            
$data['kw']=$this->Page->kw;
            
$data['body']=$this->Page->body;
            
$data['menu']=$this->Page->setMenu();
            
$data['subMenu']=$this->Page->childPages;
            
$data['newsList']=$this->MNews->getNewsByUserID($this->session->userdata('user_id'));
            
$data['contentView']='admin/news_add';
            
$this->load->view('template',$data);
        
}        
    }
 Signature 

Branson Web Design
Handmade Fashion Jewelry

 
Posted: 30 November 2009 11:58 PM   [ Ignore ]   [ # 3 ]   [ Rating: 0 ]
Avatar
Joined: 2008-09-07
119 posts

And the form code:

echo validation_errors();
if(
$this->session->flashdata('fail_string')){$this->load->view('error_div');}
if($this->session->flashdata('message_string')){$this->load->view('message_div');}
$date_month 
= array('1'=>'January','2'=>'February','3'=>'March','4'=>'April','5'=>'May','6'=>'June','7'=>'July','8'=>'August','9'=>'September','10'=>'October','11'=>'November','12'=>'December');
for(
$i=1;$i<=31;$i++){$date_date[$i]=$i;}
$yearb 
date('Y',strtotime('-5 year'));
for(
$i=1;$i<=15;$i++){$date_year[$yearb]=$yearb;$yearb++;}
$hidden 
= array('token'=>$token,'id'=>'','user_id'=>$this->session->userdata('user_id'),'date_added'=>date('Y-m-d H:i:s'));
$atts = array('id' => 'addNewsForm');
echo 
form_open(site_url('admin/news/add'),$atts,$hidden);
echo
"<table class='formTable'><tr><td>";
$nt = array('name'=>'news_title','id'=>'news_title','size'=>'70','value'=>set_value('news_title'));
echo 
form_label('Title: (63 Characters or less)','news_title')."<br/>";
echo 
form_input($nt)."<br/><br/>";
if(!(
set_value('active'))){
    $actcheckno
=FALSE;
    
$actcheckyes=TRUE;
}else{
    $actcheckyes
=FALSE;
    
$actcheckno=TRUE;    
}
$actn
=array('name'=>'active','id'=>'active_0','checked'=>$actcheckno,'value'=>0);
$acty=array('name'=>'active','id'=>'active_1','checked'=>$actcheckyes,'value'=>1);
echo
"Activate this news item? ";
echo 
form_label('Yes:','active_1');
echo 
form_radio($acty,$acty['value'],set_radio($acty['name'],$acty['value'],$actcheckyes));
echo 
form_label('No:','active_0');
echo 
form_radio($actn,$actn['value'],set_radio($actn['name'],$actn['value'],$actcheckno))."<br/><br/>";
echo 
form_label('Date: (The date you want the activated item to begin showing)')."<br/>";
echo 
form_dropdown('news_month',$date_month,set_value('news_month',date('m')))." ";
echo 
form_dropdown('news_date',$date_date,set_value('news_date',date('d')))." ";
echo 
form_dropdown('news_year',$date_year,set_value('news_year',date('Y')))."<br/><br/>";
$npu=array('name'=>'userfile','id'=>'userfile','size'=>'60','value'=>set_value('userfile'));
echo 
form_label('Image to show: ');
echo 
form_upload($npu)."<br/><br/>";
$nd=array('name'=>'news_desc','id'=>'news_desc','rows'=>'4','value'=>set_value('news_desc'));
echo 
form_label('Description: (A summarization of the news item less than 255 characters)','news_desc')."<br/>";
echo 
form_textarea($nd)."<br/><br/>";
$nb=array('name'=>'news_body','id'=>'news_body','value'=>set_value('news_body'));
echo 
form_label('Body: (The news item contents up to 65,000 characters)','news_body')."<br/>";
echo 
form_textarea($nb)."<br/><br/>";
echo
"</td></tr><tr><td colspan='2' class='buttonCell'>";
echo
"<br/>";
echo 
form_submit('submit','Save News Item');
echo
"</td></tr></table>";
echo 
form_close(); 
 Signature 

Branson Web Design
Handmade Fashion Jewelry

 
Posted: 01 December 2009 04:21 AM   [ Ignore ]   [ # 4 ]   [ Rating: 0 ]
Joined: 2009-11-27
5 posts

I have same problem. I don’t want the the file field to be required. But I alway get problem with error message “You did not select a file to upload.”

 
Posted: 01 December 2009 05:39 AM   [ Ignore ]   [ # 5 ]   [ Rating: 0 ]
Avatar
Joined: 2008-09-11
758 posts

hi first of all you have to make your form multipart right now in form code you are using

form_open(action); 

change it to multipart if you are using file field type.

form_open_multipart(action); 

please check user guide
http://ellislab.com/codeigniter/user-guide/helpers/form_helper.html

 Signature 

CI,JQuery,Google Maps | widget with CI loader | Thumbnail, Image Resize, Image Crop Helper | CI shortcode

 
Posted: 01 December 2009 10:34 AM   [ Ignore ]   [ # 6 ]   [ Rating: 0 ]
Avatar
Joined: 2008-09-07
119 posts

Thanks for the comments and help. I appreciate it. I recently changed it to form_open to test something out and hadn’t changed it back before posting the code.

However, that’s not the cause of the issue I have described. It doesn’t work with the multipart open function either.

 Signature 

Branson Web Design
Handmade Fashion Jewelry

 
Posted: 01 December 2009 10:39 AM   [ Ignore ]   [ # 7 ]   [ Rating: 0 ]
Joined: 2009-04-21
390 posts
if(!empty($_FILES))
{
   
//run upload
 Signature 

I love the smell of code in the morning.

 
Posted: 01 December 2009 10:41 AM   [ Ignore ]   [ # 8 ]   [ Rating: 0 ]
Avatar
Joined: 2008-09-07
119 posts

Genjo, you know what I am talking about then. It just doesn’t make any sense that the file upload would have to be used by itself.

It works great by itself, however, if you look in the documentation, there isn’t an example of how to use it in a form with other fields. It seems to be strictly for uploading files not part of another form.

 Signature 

Branson Web Design
Handmade Fashion Jewelry

 
Posted: 01 December 2009 10:43 AM   [ Ignore ]   [ # 9 ]   [ Rating: 0 ]
Avatar
Joined: 2008-09-07
119 posts

Thanks überfuzz, I’ll give it a shot and see if that solves the problem.

 Signature 

Branson Web Design
Handmade Fashion Jewelry

 
Posted: 01 December 2009 10:55 AM   [ Ignore ]   [ # 10 ]   [ Rating: 0 ]
Joined: 2009-04-21
390 posts

Well you’re sniffing around issues that are a bit dodgy in CI. I don’t think there is a easy all-out-CI-way to work this. However, with a little help from the core php library you should be fine.

 Signature 

I love the smell of code in the morning.

 
Posted: 01 December 2009 11:17 AM   [ Ignore ]   [ # 11 ]   [ Rating: 0 ]
Avatar
Joined: 2008-09-07
119 posts

Well, I tried

if(!empty($_FILES)){
  
// Do upload

and it still errors out.

It seems like the issue is happening with the validation object(s).

 Signature 

Branson Web Design
Handmade Fashion Jewelry

 
Posted: 01 December 2009 11:22 AM   [ Ignore ]   [ # 12 ]   [ Rating: 0 ]
Joined: 2009-04-21
390 posts
wowdezign - 01 December 2009 04:17 PM

It seems like the issue is happening with the validation object(s).

Exactly how did you incorporate it in your code..?

if(!empty($_FILES))
{
   
//put the code that's doing the upload here
 Signature 

I love the smell of code in the morning.

 
Posted: 01 December 2009 11:59 AM   [ Ignore ]   [ # 13 ]   [ Rating: 0 ]
Avatar
Joined: 2008-09-07
119 posts

Okay. I got a solution. There are probably other solutions, but I can explain why it was failing for me.

The upload field gets put into $_FILES even if it is empty and the error and size are set to 4 and 0 respectively Here is the do_upload function from CI:

function do_upload($field 'userfile'){
    
// Is $_FILES[$field] set? If not, no reason to continue.
    
if ( ! isset($_FILES[$field])){
        $this
->set_error('upload_no_file_selected');
        return 
FALSE;
    
}
    
// Is the upload path valid?
    
if ( ! $this->validate_upload_path()){
        
// errors will already be set by validate_upload_path() so just return FALSE
        
return FALSE;
    
}
    
// Was the file able to be uploaded? If not, determine the reason why.
    
if ( ! is_uploaded_file($_FILES[$field]['tmp_name'])){
        $error 
= ( ! isset($_FILES[$field]['error'])) ? $_FILES[$field]['error'];
        switch(
$error){
            
case 1:    // UPLOAD_ERR_INI_SIZE
                
$this->set_error('upload_file_exceeds_limit');
                break;
            case 
2// UPLOAD_ERR_FORM_SIZE
                
$this->set_error('upload_file_exceeds_form_limit');
                break;
            case 
3// UPLOAD_ERR_PARTIAL
               
$this->set_error('upload_file_partial');
                break;
            case 
4// UPLOAD_ERR_NO_FILE
               
$this->set_error('upload_no_file_selected');
                break;
            case 
6// UPLOAD_ERR_NO_TMP_DIR
                
$this->set_error('upload_no_temp_directory');
                break;
            case 
7// UPLOAD_ERR_CANT_WRITE
                
$this->set_error('upload_unable_to_write_file');
                break;
            case 
8// UPLOAD_ERR_EXTENSION
                
$this->set_error('upload_stopped_by_extension');
                break;
            default :   
$this->set_error('upload_no_file_selected');
                break;
        
}
        
return FALSE;
    

When I submitted my form with an empty upload field I got the following for $_FILES:

Array
(
    
[userfile] => Array
        (
            
[name] => 
            
[type] => 
            
[tmp_name] => 
            
[error] => 4
            [size] 
=> 0
        
)

So the solution for me was to do:

if($_FILES['userfile']['error'!= 4){
  
// Do upload here

Like I said before. There are probably better ways to do this, but My form is working now. Hopefully I won’t find something I overlooked later and get red face.

 Signature 

Branson Web Design
Handmade Fashion Jewelry

 
Posted: 01 December 2009 12:20 PM   [ Ignore ]   [ # 14 ]   [ Rating: 0 ]
Avatar
Joined: 2008-09-07
119 posts

My thanks to you überfuzz for putting me on the right track. I hadn’t thought to look to the $_FILES superglobal.

I was missing the obvious. Namely that the $_POST and $_FILES are separate even though they both are submitted through a form.

DUH! rolleyes .

Sometimes my brain cramps!  shut eye

 Signature 

Branson Web Design
Handmade Fashion Jewelry

 
Posted: 01 December 2009 01:57 PM   [ Ignore ]   [ # 15 ]   [ Rating: 0 ]
Joined: 2009-04-21
390 posts

Oki, I guess you could ease down my curiosity then. (To lazy to test it!) Is the $_FILES array sent if the user chose to skip the file input in the form?

 Signature 

I love the smell of code in the morning.

 
1 of 2
1