Upload an image to two different paths

2020-02-15 03:37发布

问题:

How to upload an image and save it in two different folders, ./imgup/web/data_dinamis/ and ./imgup/web/video/ ?

My code to upload image :

$config['upload_path'] = './imgup/web/data_dinamis/'; 
$config['upload_path'] = './imgup/web/video/'; 
$config['allowed_types'] = '*'; 
$config['file_name'] = $nama_baru;

$this->load->library('upload',$config);
$this->upload->do_upload('file');
$this->upload->display_errors();
$berita = array(
 'user_id' =>  $this->session->userdata('user')->user_id,
 'kategori_id' => $this->input->post('kategori_id'),
 'judul' => $this->input->post('judul'),
 'gambar' =>  $nama_baru,
);

All images are saved only in './imgup/web/data_dinamis/', but not in './imgup/web/video/'.

回答1:

the easiest would be to use ->do_upload() for each of the path you might want to upload to:

$p1='./imgup/web/data_dinamis/';
$p2='./imgup/web/video/';

//create an array of pathes:
$p=array($p1, $p2);

// get length of array
$c=count($p);

// loop through
for ($i=0;$i<$c;$i++){    
  $config['upload_path'] =$p[$i];
  $config['allowed_types'] = '*'; 
  $config['file_name'] = $nama_baru;

  $this->load->library('upload',$config);
  $this->upload->initialize($config);
  $this->upload->do_upload('file');
  $this->upload->display_errors();
}

$berita = array(
   'user_id' =>  $this->session->userdata('user')->user_id,
   'kategori_id' => $this->input->post('kategori_id'),
   'judul' => $this->input->post('judul'),
   'gambar' =>  $nama_baru,
);

note: after $this->load->library('upload',$config); use $this->upload->initialize($config); This is useful if you auto-load the class, see docs here