Codeigniter: unable to display the uploaded image

2019-09-19 00:38发布

问题:

From my below code i am able to upload images with spaces and capitalizing subsequent words, but if i try to view such images into my view page then its not visible. I am getting error like The URI you submitted has disallowed characters.

I am displaying images like <img src="<?php echo base_url().'uploads/avatar/'.$avatar?>"/> So how can i fix this error, to allow img tag to read image name with spaces and capitalizing subsequent words.

Or alternative solution, How how can i remove any spaces or capitalizing subsequent words with the image name while uploading?

I am uploading file with the below code.

   function do_upload()
        { 
         $this->load->library('form_validation'); 

        if((isset($_FILES['userfile']['size'])) && ($_FILES['userfile']['size'] > 0))
            {
                 $this->form_validation->set_error_delimiters('<li  class="errorlist">', '</li>')->set_rules('userfile', 'New Image', 'trim|callback_valid_upload_userfile');   
            }    
      $uid=$this->session->userdata('userid');
    $config['upload_path'] = './uploads/avatar/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = '5000'; 
    $this->load->library('upload', $config);  

 if ( $this->input->post('user_id') && $this->form_validation->run() == TRUE)
 {  
         $avatar= $_FILES['userfile']['name'];  //getting the file name  
          $this->loginmodel->update_user_basic_info($uid); //update both 

    }

回答1:

That's pretty simple, use:

$config['remove_spaces'] = TRUE;

So you have to take the filename from $this->upload->data() and not from $_FILES after the upload process.



回答2:

If you'd like to generate friendly image filenames that will play nice with URLs...Perhaps you could extend CodeIgniter's URL helper to contain a function called slugify(), for instance.

Create MY_url_helper.php in application/helpers/ directory. The contents of this file:

<?php
function slugify($text){ 
  // replace non letter or digits by -
  $text = preg_replace('~[^\\pL\d]+~u', '-', $text);
  // trim
  $text = trim($text, '-');
  // transliterate
  $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
  // lowercase
  $text = strtolower($text);
  // remove unwanted characters
  $text = preg_replace('~[^-\w]+~', '', $text);
  if (empty($text)) return "";
  return $text;
}

Next, autoload the url helper by adding the entry in config/autoload.php... for example: $autoload['helper'] = array('html', 'url', ...);

Finally, use slugify()...

$image1= slugify($_FILES['userfile']['name']);

As for explaining how each step of slugify works, it's really embedded in the comments. It takes the input filename argument and preps it into a more URL friendly equivalent one operation at a time.