Codeigniter ile Çoklu Resim Yükleme – 2
Etiketler : resim yukle, çoklu upload, çoklu resim, codeigniter upload class, upload, codeigniter
Görüntülenme : 1410
Daha önce yazmış olduğum Codeigniter ile Çoklu Resim Yükleme yazıda codeigniter ile çoklu upload etmekten bahsetmiştim . Fakat daha önceki yazımda inputlarımızın name degerlerini her resim için ayrı bir isim vererek yapıyorduk . Şöyle bir örnek ile hatırlatayım .
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="resim_1">
<input type="file" name="resim_2">
</form>Yukarıdaki formdan gelen dosyaları codeigniter upload sınıfı ile yüklemek için her defasında dosyanın name degerini do_upload() fonksiyonuna göndermek zorunda kalıyorduk.
<?php
$config['upload_path'] = 'uploads';
$this->CI->load->library('upload', $config);
$this->CI->upload->do_upload("resim_1") ;
$this->CI->upload->do_upload("resim_2") ;
?>
Formumuzdaki name değerlerini name="resim[]" şeklinde isimlendirerek çoklu resim yüklemek için codeigniterin upload sınıfını genişleteceğiz. Bunun için öncelikle application->libraries dizini altına MY_upload.php adında yeni bir dosya oluşturuyoruz. MY_upload.php dosyasında do_upload fonksiyonuna ekstra parametre ekleyerek override edeceğiz "do_upload($files="resim", $i=0)" . do_upload() fonksiyonunu override ederken codeigniterin kendi orjinal uplad sınıfındaki do_upload() fonksiyonundan farklı olarak yaptığımız değişiklere aşağıda değineyim.
do_upload() Fonksiyonunda Yapılan Değişiklikler
Fonksiyonumuza gelen dosya indexi için $i adında ikinci bir parametre ekliyoruz
function do_upload($field = 'userfile', $i=0)
{
.
.
.
}
161. satırının yeni hali
if ( ! is_uploaded_file($_FILES[$field]['tmp_name'][$i]))
163. satırının yeni hali
$error = ( ! isset($_FILES[$field]['error'][$i])) ? 4 : $_FILES[$field]['error'][$i];
196. 197. ve 198. satırların yeni hali
$this->file_temp = $_FILES[$field]['tmp_name'][$i];
$this->file_size = $_FILES[$field]['size'][$i];
$this->file_type = preg_replace("/^(.+?);.*$/", "1", $_FILES[$field]['type'][$i]);200. satırın yeni hali
$this->file_name = $this->_prep_filename($_FILES[$field]['name'][$i]);
My_upload.php
MY_upload.php dosyasının son halini bu adresten indirebilirsiniz.
<?php
if (!defined('BASEPATH')) exit('No direct access allowed.');
class MY_upload extends CI_upload {
/**$this->CI->
* Perform the file upload
*
* @access public
* @return bool
*/
function do_upload($field = 'userfile', $i=0)
{
// 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'][$i]))
{
$error = ( ! isset($_FILES[$field]['error'][$i])) ? 4 : $_FILES[$field]['error'][$i];
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;
}
// Set the uploaded data as class variables
$this->file_temp = $_FILES[$field]['tmp_name'][$i];
$this->file_size = $_FILES[$field]['size'][$i];
$this->file_type = preg_replace("/^(.+?);.*$/", "1", $_FILES[$field]['type'][$i]);
$this->file_type = strtolower(trim(stripslashes($this->file_type), '"'));
$this->file_name = $this->_prep_filename($_FILES[$field]['name'][$i]);
$this->file_ext = $this->get_extension($this->file_name);
$this->client_name = $this->file_name;
// Is the file type allowed to be uploaded?
if ( ! $this->is_allowed_filetype())
{
$this->set_error('upload_invalid_filetype');
return FALSE;
}
// if we're overriding, let's now make sure the new name and type is allowed
if ($this->_file_name_override != '')
{
$this->file_name = $this->_prep_filename($this->_file_name_override);
$this->file_ext = $this->get_extension($this->file_name);
if ( ! $this->is_allowed_filetype(TRUE))
{
$this->set_error('upload_invalid_filetype');
return FALSE;
}
}
// Convert the file size to kilobytes
if ($this->file_size > 0)
{
$this->file_size = round($this->file_size/1024, 2);
}
// Is the file size within the allowed maximum?
if ( ! $this->is_allowed_filesize())
{
$this->set_error('upload_invalid_filesize');
return FALSE;
}
// Are the image dimensions within the allowed size?
// Note: This can fail if the server has an open_basdir restriction.
if ( ! $this->is_allowed_dimensions())
{
$this->set_error('upload_invalid_dimensions');
return FALSE;
}
// Sanitize the file name for security
$this->file_name = $this->clean_file_name($this->file_name);
// Truncate the file name if it's too long
if ($this->max_filename > 0)
{
$this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename);
}
// Remove white spaces in the name
if ($this->remove_spaces == TRUE)
{
$this->file_name = preg_replace("/s+/", "_", $this->file_name);
}
/*
* Validate the file name
* This function appends an number onto the end of
* the file if one with the same name already exists.
* If it returns false there was a problem.
*/
$this->orig_name = $this->file_name;
if ($this->overwrite == FALSE)
{
$this->file_name = $this->set_filename($this->upload_path, $this->file_name);
if ($this->file_name === FALSE)
{
return FALSE;
}
}
/*
* Move the file to the final destination
* To deal with different server configurations
* we'll attempt to use copy() first. If that fails
* we'll use move_uploaded_file(). One of the two should
* reliably work in most environments
*/
if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name))
{
if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name))
{
$this->set_error('upload_destination_error');
return FALSE;
}
}
/*
* Run the file through the XSS hacking filter
* This helps prevent malicious code from being
* embedded within a file. Scripts can easily
* be disguised as images or other file types.
*/
if ($this->xss_clean == TRUE)
{
$this->do_xss_clean();
}
/*
* Set the finalized image dimensions
* This sets the image width/height (assuming the
* file was an image). We use this information
* in the "data" function.
*/
$this->set_image_properties($this->upload_path.$this->file_name);
return TRUE;
}
}
MY_upload.php dosyasının son halini bu adresten indirebilirsiniz. Şimdi yapığımız değilikleri örnek bir uygulama ile test edelim .
resim_yukle_view.php
View dosyamız :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="<?php echo site_url('resim_yukle'); ?>" method="post" enctype="multipart/form-data">
<input type="file" name="resim[]">
<input type="file" name="resim[]">
<input type="file" name="resim[]">
<input type="submit" value="Yükle">
</form>
</body>
</html>
resim_yukle.php
Controller dosyamızda formdan gelen resimleri for döngüsü ile do_upload() fonksiyonuna parametreleri göndererek resimleri yükleyeceğiz.
<?php
class Resim_yukle extends Controller
{
function __Construct()
{
parent::Controller();
}
function index()
{
if ( $_FILES ) {
$config['upload_path'] = 'uploads';
$this->CI->load->library('upload', $config);
for($i=0; $i < count($_FILES['resim']['tmp_name']); $i++)
{
$this->upload->do_upload('resim', $i);
}
}
$this->load->view('yonetim/resim_yukle_view', $data, TRUE);
}
}
Sonuç
Codeigniterin upload sınıfını genişleterek hem codeigniterin kendi do_upload() fonksiyonunu hemde kendi yazdığımız do_upload() fonksiyonumuzu kullanabileceğiz. Eğer do_upload("resim") şeklinde tek parametre gönderirsek codeigniterin kendi upload sınıfındaki fonksiyon çalışacak, do_upload("resim",1) şeklinde 2 parametre gönderirsek MY_upload.php dosyasındaki fonksiyon çalışacaktır. Faydalı olması dileğiyle :) iyi çalışmalar .
Ben değişiklikleri codeigniterin kendi upload sınıfı içerisindeki do_upload() fonksiyonunu değiştirerek yapmıştım ama sayın Fatih Bazman'ın uyarısıyla MY_upload.php dosyasını oluşturarak upload sınıfını genişleterek değişiklikleri uyguladım. Böylece Codeigniteri güncellediğimiz zaman oluşacak sorunların önüne geçmiş olduk. Fatih Bazman'a teşekkürlerimi sunarım.
Paylaş
Benzer Yazılar
Yorumlar >> (7 Yorum)
Fatih 21 Şub 2011, Pt 20:55 tarihinde yazılmış.Serkan,Çözümünü paylaştığın için teşekkürler. Ancak, CodeIgniter Core da yapacağın değişiklikler için MY_Upload.php dosyasını yazarak bu fonskiyonu oraya taşımanı öneririm.Böylelikle ileride CI upgradelerinde yaşayacağın sıkıntıların önüne geçmiş olursun.
alexander 21 Şub 2011, Pt 20:56 tarihinde yazılmış.çok haklısınız fatih bey yazımıda sizin dediğiniz şekilde düzenleyeyim. Çok teşekkürler .
osman kara 23 Oca 2012, Pt 23:19 tarihinde yazılmış.Bunu ben anlamadım. 3 tane resım gondermem lazım ve 3 resmın de
1 orjınalı
2 100x100 luk kucuk halı lazım.bunu dosya olarak paylasa bılırmısınız ?
alexander 24 Oca 2012, Sa 00:32 tarihinde yazılmış.takıldığınız noktada yardımcı olmaya çalışırım ama bu şekilde direkt kod isterseniz üzgünüm yardımcı olamam.
alexander 24 Oca 2012, Sa 13:10 tarihinde yazılmış.$config[‘upload_path’] = ‘./upload/resim_upload’; değerini doğru verdiğinden emin ol.
Bir de bu şekilde vermeyi dene.
$config['upload_path'] = 'upload/resim_upload';
hatayı ekrana yazdırmayı dene hataya göre sorunu bulmaya çalışalım.
osman kara 24 Oca 2012, Sa 15:03 tarihinde yazılmış.sımdı
if (!$this->upload->do_upload('resim', $i)) {
echo '<div class="form-message error">' . $this->upload->display_errors() . '</div>';
}
de hata sorgulatıyorum sanırm.
bu kodları normal olarak denedımde yoluna gıdıyor :S ama
osman kara 25 Oca 2012, Ça 00:00 tarihinde yazılmış.Yok olmuyor :S kodları da gonderım :)
ıstedıgım olay su aslında
3 resım gondermek
ve bu 3 resmın 3 tanede kucuk resmı olucak onları gondermek
3 kucuk resmı gectım 3 resmı gonderemıyorum..
tek resım gondrmekte yada tek resmı gonderıp onun 3 kucugunu yapmakta sorun yok
Yorum Yap
Yorum Yazarken
Basit Html etiketlerini kullanabilirsiniz.
Kodlarınızı <pre></pre> etiketleri arasına yazınız.