修改我的图像上传器

时间:2011-07-19 22:44:37

标签: php codeigniter

目前,我有一些代码可以执行以下操作:

我可以编辑,我可以为这个特定的房子添加上传/编辑一个图像的房屋销售,然后在创建过程中创建缩略图,然后将原始文件名和缩略图名称保存到名为 imagename 和 imagethumb

注意:添加和编辑单独的页面

我的想法是:

我将创建另一个页面,其中包含已放入下拉菜单中的房屋名称,因此当选择一个并选择图像时,它们将上传。

我的问题是:

  1. 我对于修改数据库以实现此更改的最佳方法感到困惑。

  2. 如何修改我的PHP代码以处理多个文件(如何处理多个图像然后传递图像以上传大小调整等)什么是最佳选项? - 在我的想法中?

  3. 我可以举一个例子来说明我应该做些什么来解决这个问题。

  4. 我已添加了我的添加促销的模型视图和控制器(作为示例),但我还需要为相应的销售编辑图像。

    型号:

    class Sales_model extends CI_Model
    {
    
        function __construct() {
                parent::__construct();
        }
    
        function getSalesPage($id = NULL) {
    
            $query = $this->db->get_where('sales', array('id' => $id), 1);
            if($query->num_rows() == 1) return $query->row();
    
        } # End getSalesPage
    
        function getSalesPages($id = NULL) { // $id does nothing
            $query = $this->db->get('sales');
            if($query->num_rows() > 0) return $query->result();
    
        } # End getSalesPages
    
        function getSalesContent($id = NULL) {
            $this->db->where('id', $id);
            $query = $this->db->get('sales', 1);
    
            if($query->num_rows() > 0) {
                $row = $query->result_array();
                return $row;
            }else{
                return FALSE;
            } # End IF
        } # End getSalesContent
    
    
        function addSale($data = NULL) {
            $this->db->insert('sales', $data);
            return TRUE;
        } # End Add Sale    
    
        function updateSale($id, $content) { //Content id from being passed
    
            $this->db->where('id', $id);  // selecting the $id to update
            $update = $this->db->get('sales'); // What does $update = well it = get the db sales
            $row = $update->row_array(); // what does $row mean = well it gets the row as an array
    
            if($update->num_rows() > 0) {
    
                if(isset($content['imagename']) && isset($content['thumbname'])) {
    
                #lets delete the image
                unlink("/includes/uploads/gallery/".$row['imagename']);
                #lets delete the thumb.
                unlink("/includes/uploads/gallery/thumbs/".$row['thumbname']);
            }
                    $this->db->where('id', $id);
                    if($this->db->update('sales', $content))
                    {
    
                        return TRUE;
                    }
                    else
                    {
                        return FALSE;
                    }
                } # End IF
        } # End Update
    
        function deleteSale($id){
    
            $this->db->where('id', $id);
            $q = $this->db->get('sales');
            $row = $q->row_array();
    
            if ($q->num_rows() > 0){
                //delete from the database
                $this->db->where('id', $id); 
                $this->db->delete('sales');
    
                //lets delete the image
                unlink("includes/uploads/sales/".$row['imagename']);
                //lets delete the thumb.
                unlink("includes/uploads/sales/thumbs/".$row['thumbname']);
            }//END if num_rows
        }//END function deleteSale($id)
    } # End Model
    

    查看:

        <?php
    //Setting form attributes
    $formAddSale = array('id' => 'addSale', 'name' => 'addSale');
    $saleName = array('id' => 'name', 'name' => 'name','class' => 'validate[required[custom[onlyLetterSp]]]', 'value' => set_value('name'));
    $saleLocation = array('id' => 'location', 'name' => 'location','class' => 'validate[required[custom[onlyLetterSp]]]', 'value' => set_value('location'));
    $saleBedrooms = array('id' => 'bedrooms','name' => 'bedrooms','class' => 'validate[required[custom[number]]]', 'value' => set_value('bedrooms'));
    $saleBathrooms = array('id' => 'bathrooms','name' => 'bathrooms','class' => 'validate[required[custom[number]]]', 'value' => set_value('bathrooms'));
    $saleCondition = array('id' => 'condition','name' => 'condition','class' => 'validate[required[custom[onlyLetterSp]]]', 'value' => set_value('condition'));
    $saleImage = array('id' => 'userfile', 'name'=> 'userfile');
    $salePrice = array('id' => 'price','name' => 'price','class' => 'validate[required[custom[number]]]','value' => set_value('price'));
    $saleDescription = array('id' => 'description','name' => 'description','class' => '', 'value' => set_value('description'));
    $saleSubmit = array('id' => 'submit', 'name'=> 'submit', 'value' => 'Add Sale');
    ?>
    
    <div id ="formLayout">
        <?php
        if($success == TRUE) {
        echo '<section id = "validation">Sale Added</section>'; 
        }
        echo '<section id = "validation">'.$message['imageError'].'</section>';
        ?>
    <?php echo form_open_multipart('admin/addsale/', $formAddSale); ?>
    <?php echo form_fieldset(); ?>
    
    <?php echo form_label('Name:','name'); ?>
    <?php echo form_input($saleName); ?>
    <div id="errorName"><?php echo form_error('name'); ?></div>
    <span class="small">Required Field - Text</span>
    
    <?php echo form_label('Location:','location');?>
    <?php echo form_input($saleLocation);?>
    <div id="errorLocation"><?php echo form_error('location'); ?></div>
    <span class="small">Required Field - Text</span>
    
    <?php echo form_label('Bedrooms: ','bedrooms');?>
    <?php echo form_input($saleBedrooms);?>
    <div id="errorBedrooms"><?php echo form_error('bedrooms'); ?></div>
    <span class="small">Required Field - Number</span>
    
    <?php echo form_label('Bathrooms: ','bathrooms');?>
    <?php echo form_input($saleBathrooms);?>
    <div id="errorBathrooms"><?php echo form_error('bathrooms'); ?></div>
    <span class="small">Required Field - Number</span>
    
    <?php echo form_label('Condition: ','condition');?>
    <?php echo form_input($saleCondition);?>
    <div id="errorCondition"><?php echo form_error('condition'); ?></div>
    <span class="small">Required Field - Text</span>
    
    <?php echo form_label('Price: ','price');?>
    <?php echo form_input($salePrice);?>
    <div id="errorPrice"><?php echo form_error('price'); ?></div>
    <span class="small">Required Field - Number</span>
    
    <?php echo form_label('Image: ','userfile');?>
    <?php echo form_upload($saleImage);?>
    <div id="errorUserfile"><?php echo form_error('userfile'); ?></div>
    <span class="small">Required Field - 1MB Max Size</span>
    
    <?php echo form_label('Description: ','description');?>
    <div id="errorDescription"><?php echo form_error('description'); ?></div>
    <span class="small">Required Field - Text</span>
    <?php echo form_textarea($saleDescription);?>
    <script type="text/javascript">CKEDITOR.replace('description');</script>
    
    <?php echo form_submit($saleSubmit);?>
    <?php echo form_fieldset_close(); ?>
    <?php echo form_close(); ?>
    </div>
    

    控制器:

    class Addsale extends CI_Controller 
    { 
        function __construct()
        { 
            parent::__construct(); 
        } 
    
        function index() 
        { 
            if(!$this->session->userdata('logged_in'))redirect('admin/home');
    
                # Main Data
    
                $data['title'] = 'Add Sale: ';
    
                //Set Validation
    
                $this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean'); 
                $this->form_validation->set_rules('location', 'Location', 'trim|required|xss_clean'); 
                $this->form_validation->set_rules('bedrooms', 'Bedrooms', 'trim|numeric|required|xss_clean'); 
                $this->form_validation->set_rules('bathrooms', 'Bathrooms', 'trim|numeric|required|xss_clean'); 
                $this->form_validation->set_rules('condition', 'Condition', 'trim|required|xss_clean'); 
                $this->form_validation->set_rules('description', 'Description', 'trim|required|xss_clean'); 
                $this->form_validation->set_rules('price', 'Price', 'trim|required|xss_clean');
    
                if($this->form_validation->run()) {
                //Set File Settings 
                $config['upload_path'] = 'includes/uploads/sales/'; 
                $config['allowed_types'] = 'jpg|png'; 
                $config['remove_spaces'] = TRUE;
                $config['overwrite'] = TRUE;
                $config['max_size'] = '1024';
                $config['max_width'] = '1024'; 
                $config['max_height'] = '768'; 
    
                $this->load->library('upload', $config);
    
                if(!$this->upload->do_upload()) {
    
                    $data['message'] = array('imageError' => $this->upload->display_errors());
                } // Upload error end
                else{
                        $data = array('upload_data' => $this->upload->data());
                        $data['success'] = TRUE;
                        $config['image_library'] = 'GD2';
                        $config['source_image'] = $this->upload->upload_path.$this->upload->file_name;
                        $config['new_image'] = 'includes/uploads/sales/thumbs/';
                        $config['create_thumb'] = 'TRUE';
                        $config['thumb_marker'] ='_thumb';
                        $config['maintain_ratio'] = 'FALSE';
                        $config['width'] = '150';
                        $config['height'] = '150';
    
                        $this->load->library('image_lib', $config);
                        $this->image_lib->resize();
    
    
                    $file_info = $this->upload->data(); 
    
                    $this->db->escape($content);
    
                    $content = array(   
                        'name' => $this->input->post('name', TRUE), 
                        'location' => $this->input->post('location', TRUE), 
                        'bedrooms' => $this->input->post('bedrooms', TRUE), 
                        'bathrooms' => $this->input->post('bathrooms', TRUE), 
                        'condition' => $this->input->post('condition', TRUE), 
                        'description' => $this->input->post('description', TRUE), 
                        'price' => $this->input->post('price', TRUE), 
                        'imagename' =>$file_info['file_name'],
                        'thumbname' =>$file_info['raw_name'].'_thumb'.$file_info['file_ext']
                    );          
    
                    $this->sales_model->addSale($content);
                    }#end else
                    } # End Form Validation       
                    $data['content'] = $this->load->view('admin/addsale', $data, TRUE);
                    $data['sales_pages'] = $this->sales_model->getSalesPages();
                    $data['cms_pages'] = $this->navigation_model->getCMSPages();
                    $this->load->view('admintemplate', $data);
    
                } # End Index Function 
            } # End Controller
    

1 个答案:

答案 0 :(得分:0)

对于处理下拉列表,我认为这很简单。但相关的多上传内容,你可以使用类似的东西......

在您的视图中

<?php echo form_label('Image: ','userfile1');?>
<?php echo form_upload('userfile1');?>
<?php echo form_label('Image: ','userfile2');?>
<?php echo form_upload('userfile2');?>
<!-- and so on -->
<span class="small">Required Field - 1MB Max Size</span>

然后在你的控制器中,你可以这样做

//Set File Settings 
$config['upload_path'] = 'includes/uploads/sales/'; 
$config['allowed_types'] = 'jpg|png'; 
$config['remove_spaces'] = TRUE;
$config['overwrite'] = TRUE;
$config['max_size'] = '1024';
$config['max_width'] = '1024'; 
$config['max_height'] = '768'; 

$this->load->library('upload', $config);

// Validate files for upload section...
$success = array();
$errors = array();
$updload_files = array(
        'userfile1' => $_FILES['userfile1'],
        'userfile2' => $_FILES['userfile2'],
        // You can add more
        );

foreach($updload_files as $field => $updload_file)
{
    // Only process submitted file
    if($updload_file['error'] == 0)
    {
       // If there is an error, save it to error var
       if( ! $this->upload->do_upload($field) )
       {
           $errors[] = 'Failed to upload '.$field;  
       }

       // Use this to get the new file info if you need to insert it in a database
       $success[] = array( 'Success to upload '.$field => $this->upload->data());
    } 
    else 
    {
       $errors[] = $field . ' contain no data';  
    }
}
// Heres you could gettin know whats happen
var_dump($errors);
var_dump($success);