2013-07-28 63 views
0

我有一個腳本來上傳文件使用codeigniter,但它仍然使用提交按鈕。我想上傳而不點擊提交。這是我的腳本:如何在沒有提交按鈕的情況下在codeigniter中上傳文件?

控制器/ gallery.php

<?php 
class Gallery extends CI_Controller{ 
    public function __construct() 
    { 
     parent::__construct(); 
    } 

    function index(){ 
     $this->load->model('MGallery'); 
     if($this->input->post('upload')){ 
      $this->MGallery->do_upload(); 
     } 

    $this->load->view('gallery_view'); 
    } 
} 
?> 

型號/ mgallery.php

<?php 
class MGallery extends CI_Model{ 

var $gallery_path; 

public function __construct() 
{ 
    parent::__construct(); 
    $this->gallery_path = realpath(APPPATH . '../images'); 
} 

function do_upload(){ 
    $config = array(
     'allowed_types'=>'jpg|jpeg|gif|png', 
     'upload_path' => $this->gallery_path, 
     'max_size' => 2000 
    ); 

    $this->load->library('upload',$config); 
    $this->upload->do_upload(); 
    $image_data = $this->upload->data(); 

    $config = array(
     'source_image'=> $image_data['full_path'], 
     'new_image'=>$this->gallery_path . '/thumbs', 
     'maintain_ration'=>true, 
     'width'=>160, 
     'height'=>120 
    ); 

    $this->load->library('image_lib', $config); 
    $this->image_lib->resize(); 
    } 
} 

*意見/ gallery_view.php *

<!DOCTYPE HTML> 

<html lang="en-US"> 

    <head> 
     <title>Gallery With CI</title> 
     <meta charset="UTF-8"> 
    </head> 
    <body> 
     <div id="gallery"> 
     </div> 

     <div id="upload"> 

      <?php echo form_open_multipart('gallery'); ?> 
      <?php echo form_upload('userfile');?> 

      <?php echo form_submit('upload','Upload'); ?> 
      <?php echo form_close(); ?> 

     </div> 
</body> 

如果我想讓它上傳而不提交按鈕,我該怎麼辦?

回答

1

爲了能夠上傳您的文件,您需要在瀏覽文件時觸發一些JavaScript功能。以下代碼可能會幫助您使用JQuery AJAX庫進行此操作。

$upload_field_info = array('class' => 'file_upload', 'id' => 'file_upload', 'name' => 'file_upload'); 
echo form_input($upload_field_info); 

編寫JavaScript函數在您的視圖:

$('#file_upload').change(function(){ 
var upload_data = $('#file_upload').val() 
var post_url = "<?php echo base_url();?>index.php/gallery/upload"; 
$.ajax({ 
    type: "POST", 
    url: post_url, 
    data: upload_data, 
    datatype: "json", 
    success: function(data) 
    { 
     $('#upload_result_div').html("<span class=success>File Uploaded!</span>"); 
    } 
}); 

你將需要一個名爲「上傳你的‘庫’控制器功能!

+0

你會給我更詳細的腳本在每個模型,視圖,控制器? 我已經嘗試上面的解決方案,但我上傳的圖像沒有存儲在目標文件夾中。 對不起,我還是新手.. – dyn

相關問題