Welcome Guest, Not a member yet? Register   Sign In
file uploading with text and description
#1

[eluser]swgj19[/eluser]
I am almost through building a simple gallery, but need help on the logic.
The gallery is using code from the CI file upload series.

I basically have a form that displays title, description, and image field to upload an image. I have already set up where the image uploads to a directory and makes a thumb on the server. That was not to difficult.

Now I am trying to upload a title and description with an image id stored in the db.
The image id will have to be joined with the title and description id.

I will also add validation to prevent sql injection.

So, what are the steps(logic) to assign id to an image. Store the images. Relate the title and description id to the image id. So when the gallery is viewed, the title and description will be next to the correct corresponding image.

Here is the page where the title and description will be next the image
http://www.cradlewebdesign.com/index.php/gallery/index

Thanks.


Controller
Code:
<?php
class Gallery extends CI_Controller {

function index() {
  
  $this->load->model('Gallery_model');
  
  
  
  if ($this->input->post('upload')) {
   $this->Gallery_model->do_upload();
  }
  
  $data['images'] = $this->Gallery_model->get_images();
  $data['title'] = $this->input->post('title');
  $data['title'] = $this->input->post('description');  
  
  
  $data['left_content'] = 'gallery_left';
  $data['right_content'] = 'gallery_right';
  $this->load->view('includes/template', $data);
}

}

Model
Code:
<?php
class Gallery_model extends CI_Model {

var $gallery_path;
var $gallery_path_url;

function Gallery_model() {
  parent::__construct();
  
  $this->gallery_path = realpath(APPPATH . '../images');
  $this->gallery_path_url = base_url().'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' => 150,
   'height' => 100
  );
  
  $this->load->library('image_lib', $config);
  $this->image_lib->resize();
  
}

function get_images() {
  
  $files = scandir($this->gallery_path);
  $files = array_diff($files, array('.', '..', 'thumbs'));
  
  $images = array();
  
  foreach ($files as $file) {
   $images []= array (
    'url' => $this->gallery_path_url . $file,
    'thumb_url' => $this->gallery_path_url . 'thumbs/' . $file
   );
  }
  
  return $images;
}

}

View

Code:
<div id="upload">
  &lt;?php
  echo form_open_multipart('gallery');
  //userfile is from file upload library
  echo form_input("title", "title");
  ?&gt;
        <br />
        &lt;?php
  echo form_textarea("description", "website description", "200", "200");
  ?&gt;
        <br />
        &lt;?php
  echo form_upload('userfile');
  echo form_submit('upload', 'Upload');
  echo form_close();
  ?&gt;  
</div>
#2

[eluser]swgj19[/eluser]
I just found http://ellislab.com/forums/viewthread/222115/

I will see if this answered my question.
#3

[eluser]jojo777[/eluser]
I created some time ago a simple upload form with:
- Name field for image.
- Description field image.
- Field for the file.

So when it was submited:
- It uploaded the image, checked if the image was uploaded correctly, then creates thumbnail(optional).
- If the first step worked, then takes the image name, the description, and the random name generated if it was set to insert those data in the DB.

I don't have the code here rigth now but that is the main idea, if you need more help ask Wink

PD:Sorry for my english.
#4

[eluser]swgj19[/eluser]
Here is my model. I am able to easily store the title and description, but I cannot get the path and thumb path to be stored in the db. The problem is under function store_images_db.

Code:
&lt;?php
class Gallery_model extends CI_Model {

var $gallery_path;
var $gallery_path_url;

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

function do_upload() {
  //set image configuration
  $config = array(
   'allowed_types' => 'jpg|jpeg|gif|png',
   'upload_path' => $this->gallery_path,
   'max_size' => 2000,
   'encrypt_name'  => true
  );
  
  $this->load->library('upload', $config);
  $this->upload->do_upload();
  $image_data = $this->upload->data();
  
  //set image path and make thumb
  $config = array(
   'source_image' => $image_data['full_path'],
   'new_image' => $this->gallery_path . '/thumbs',
   'maintain_ration' => true,
   'width' => 150,
   'height' => 100
  );
  
  $this->load->library('image_lib', $config);
  $this->image_lib->resize();
  
}

function store_images_db() {
  
  $this->db->insert('photos', array(
     'id' => $this->input->post('id'),
     'title' => $this->input->post('title'),
     'description' => $this->input->post('description'),
     'path' => $image_data['full_path'],
     'thumb_path'=> $image_data['file_path'] . 'thumbs/'. $image_data['file_name']
  
  //'path' => $image_data['full_path'],
  //'thumb_path' => $image_data[
));
}

function get_images() {
  
  $files = scandir($this->gallery_path);
  $files = array_diff($files, array('.', '..', 'thumbs'));
  
  $images = array();
  
  //loop images in view
  foreach ($files as $file) {
   $images []= array (
    'url' => $this->gallery_path_url . $file,
    'thumb_url' => $this->gallery_path_url . 'thumbs/' . $file
   );
  }
  
  return $images;
}

}
#5

[eluser]jojo777[/eluser]
Hi again Stephen, yur code looks similar to the one I use, the main diference is I do not store the path into DB.

I use.

Paths variables. You can pass and them to your model with getter&setter;. But i dont think its a real cause.
Code:
Private $upload_path='./assets/images/galerias/';
Private $upload_path_thumbs='./assets/images/galerias/thumbs/';

If you wan i can post my code but it doesnt store the paths, only the id, name, description and the random name generated at the upload.

Wich is the error when you try to store the path??
#6

[eluser]swgj19[/eluser]
Quote:If you wan i can post my code but it doesnt store the paths, only the id, name, description and the random name generated at the upload.

If you can show me you code that would be great. Come to think of it, there is no point storing the path, because if the path changes, then the paths in the database will be wrong.
#7

[eluser]jojo777[/eluser]
Hi again, I've some of my code here i'll put some parts maybe it can help you.

You are right. If the path is changed it would be a mess to change all the records of the database, so I prefer create a variable for the galleries and define their path, so all of them can be saved in their own directory (If you use some kind clasification like carsgallery, moviesgallery....)

Paths variables.
Code:
Private $upload_path='./assets/images/galerias/';
Private $upload_path_thumbs='./assets/images/galerias/thumbs/';

Now the upload code. In MY_Model(or MY_Controller, i think is better in model) cause was used by many of them.
Code:
// Upload Function
    // Returns $image_data['file_name'] if the upload of the image and its thumb was correct or it will return errors to the controller.
    public function subir_archivo($upload_path, $upload_path_thumbs){
        
        //empieza la subida del archivo  
        $config = array(
                'upload_path' => $upload_path,
                'allowed_types' => 'gif|jpg|png|jpeg',
                'max_size' => 1024*2,
                'max_width' => 1000, // for example
                'max_height' => 1000, // for example
                'remove_spaces' => true,
                'encrypt_name' => true
             );
        
        $this->load->library('upload', $config);
                
        if ( ! $this->upload->do_upload())
        {
            $data = $this->upload->display_errors();
            
            $datos= array (
                
                'file_name' => '',
                'error' => true,
                'data_error' => $data,              
              );
              
            return $datos;
        }else{
            $image_data= $this->upload->data();
            
            $config = array (
                 'source_image' => $image_data['full_path'],
                 'allowed_types' => 'gif|jpg|png|jpeg',
                 'new_image' => $upload_path_thumbs,
                 'maintain_ration' =>  true,
                 'width' => 150, // choose yourself
                 'height' => 100 // choose yourself
                 );
        
            $this->load->library('image_lib', $config);
            $this->image_lib->resize();
                
            
            $datos= array (
                    'file_name' => $image_data['file_name'],
                    'error' => false
                    );
            
            return $datos;
        
        }
        
    }

So now the call that launchs the image upload
Code:
$subida=$this->subir_archivo($this->upload_path, $this->upload_path_thumbs);

$image_name=$subida['file_name'];
$error=$subida['error'];

if($error==true){
$data['error'] = $subida['data_error'];
}

if ($error==false){

      $datos = array (
      'titleImg' => $this->input->post('title', true),
      'descriptionImg' => $this->input->post('description', true),
      'img' => $image_name,
      );

$this->db->insert('galeria_imagenes', $datos);

}

This should be enough for your needs.
This should work (in fact it works actually in a web) but its for single upload, If you need multiple upload at the same time the code have to be revised.

For multiple there are some alternatives, I use a code that uses twitter bootstrat and CI.

Hope the code helps.
#8

[eluser]solid9[/eluser]
@Stephen

I read your codes.
And I noticed you broke the MVC rule.
Some of your methods like do_upload() should not be in the model.
It should be in the controller or library.

And catching the data from a form is supposed to be in the controller as well,
not in the model.

The codes that should be in the model/MY_Model is the CRUD.
C = Create record
R = Read record
U = Update record
D = Delete record

Also before diving into a project.
You should have a plan. Try to visualize everything first.
And use the Divide and conquer method.
You can use flowchart but if you are in a hurry you can use the comments method.

Here is a basic example of 'Comment Method',

controller:
- catch data
- validate data
- upload image
- resize image

model:
- store info like img_id, title, image_name, description
view:
- display upload form
- display error message
- display successful upload page


I also have another solution, there are already made Image Galleries where you can incorporate to your site easily, like the one below so you don't re-invent the wheel,
http://inspirationfeed.com/resources/too...y-plugins/

Anyways if your purpose is to practice your coding skills while making your gallery then stick
with your custom gallery plan.

#9

[eluser]solid9[/eluser]
Here is another way to visualize your plan for your codes using the 'Comment method'.

Step 1 - Display Upload Form (view)
Step 2 - validate data from controller (controller)
- If it has error display form again with error
Step 3 - Capture valid data (controller)
Step 4 - resize image for thumbnail (controller)
Step 5 - store images into image_path/image_folder (controller)
step 6 - When everything is right then store information into DB. (model)
- When record insert is successful return to controller
Step 7 - If insert record is a success display 'Success Message' (view)
etc, etc, etc...

The key to right coding is to plan it ahead.
(Visualize it, you can use flowchart or Comment method).
Do it step by step, you can modify the steps above if it doesn't meet your needs.

Hope this will help you stephen.

#10

[eluser]swgj19[/eluser]
@jojo777
Thank you so much for the example. I think I now see that I just need to set the image path as a variable and simply pass to the database. I just need to tweak a couple things.
I will post my finished code soon.

@solid9
You are God sent man. I should plan better next time. I only planned a few of the steps you mentioned. I hurried because of the lack of time I have to do what I love, programming. When you manage a well known restaurant, there is not much time for anything else.
I will take what you said to heart, plan efficiently, and re-arrange the code in its proper place (MVC) and post soon. Thank you for your time.




Theme © iAndrew 2016 - Forum software by © MyBB