0

I'm a beginner and still learning to programme. I want to do something like this: https://ufile.io/z2w0l My question is how to preview a few images before uploading in the database with php,mysql? I have code but it work like this: When I choose which image i want to upload, the image doesn't display. Image is displaying when i click on submit button. I will take the picture of my layout here: https://prnt.sc/mv1ef0 (this is my form where i can upload image), https://prnt.sc/mv1erl (this is my submit button "Post"). When i click on submit button the page is refreshing and the image is displaying(like this photo): https://prnt.sc/mv1fjg I want to preview picture first: https://prnt.sc/mv1iiz (in this box) Here is my php code:

public function create() {
        $this->requireSession();
        $this->load->model('store_model');

        $visible = 0;
        if($this->input->post('is_visible') == 'on') {
            $visible = 1;
        }

        $promotion = 0;
        if($this->input->post('is_promotion') == 'on') {
            $promotion = 1;
        }

        $internal = 0;
        if($this->input->post('is_internal') == 'on') {
            $internal = 1;
        }

        $userId = $this->authorization->getUserId();
        $storeId = $this->authorization->getStore();

        $price = $this->input->post('price');
        $prev_price = $this->input->post('prev_price');
        if($promotion == 1) {
            $price = $this->input->post('prev_price');
            $prev_price = $this->input->post('price');
        }

        date_default_timezone_set('Europe/Sofia');

        $data = array( 
            'name' => $this->input->post('name'),
            'description' => $this->input->post('description'),
            'price' => $price,
            'currency' => 'BGN',
            'is_promotion' => $promotion,
            'promotion_price' => $prev_price,
            'quantity' => $this->input->post('quantity'),
            'status' => $this->input->post('status'),
            'main_image' => 0,
            'is_internal' => $internal,
            'is_visible' => $visible,
            'url_address' => $this->input->post('url'),
            'total_views' => 0,
            'total_likes' => 0,
            'total_comments' => 0,
            'product_added' => date("Y-m-d H:i:s"),
            'is_active' => 1,
            'category_id' => $this->input->post('category_id'),
            'user_id' => $this->authorization->getUserId(),
            'store_id' => $storeId,
            'brand_id' => $this->input->post('brand_id')
        );

        $this->db->insert("products", $data);
        $product_id = $this->db->insert_id();

        $this->db->query("UPDATE categories SET total_products = total_products + 1 WHERE id = " . $this->input->post('category_id'));
        $this->db->query("UPDATE stores SET total_products = total_products + 1 WHERE id = " . $storeId);
        $this->db->query("UPDATE users SET total_products = total_products + 1 WHERE id = " . $userId);

        $tags = $this->input->post('tags');
        $this->load->model('tag_model');
        $this->tag_model->updateTags($tags, $product_id);

        $this->load->model('category_model');
        $this->load->model('attribute_model');
        $attributes = $this->category_model->getOnlyAttributes($this->input->post('category_id'));
        $values = array();
        foreach($attributes as $row) {
            $values[] = array('product_id' => $product_id, 'attribute_value_id' => $this->input->post('attribute_id' . $row->attribute_id));
        }
        if($attributes) {
            $this->attribute_model->updateProductAttributes($values, $product_id);
        }

        if($_FILES["fileToUpload"]["tmp_name"]) {
            $uploadOk = 1;
            //$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
            // Check if image file is a actual image or fake image
            $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
            if($check !== false) {
                $uploadOk = 1;
            } else {
                $uploadOk = 0;
            }
            // Check file size
            if ($_FILES["fileToUpload"]["size"] > 500000) {
                $uploadOk = 0;
            }
            // Allow certain file formats
            /*if($imageFileType != "jpg") {
               $uploadOk = 0;
            }*/
            // Check if $uploadOk is set to 1
            if ($uploadOk == 1) {
                $this->db->insert('products_images', array('product_id' => $product_id));
                $insert = $this->db->insert_id();

                $target_dir = "./" . p_image_path();
                $target_file = $target_dir . '/' . $insert . '.jpg';
                move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
                $this->db->update("products", array('main_image' => $insert), array('id' => $product_id));

            }
        }

        redirect(site_url('mystore/products/edit/' . $product_id));
    }

Here is my HTML code:

<div class="item-card">
                                <div class="card-section">
                                    <div class="clearfix">
                                        <!---<div class="pull-right">
                                        <input type="file" name="fileToUpload" id="fileToUpload">
                                        </div>---->

                                        <div class="pull-right">
                                        <span class="btn btn-white upload_image" type="file"  id="fileToUpload">Upload image</span>
                                        <input class="upload_file" type="file" name="fileToUpload" id="fileToUpload" style="display:none;">
                                        </div>

                                        <h2 class="al">Images</h2>
                                    </div>
                                    <hr />
                                    <div class="item-images clearfix">
                                        <div class="empty-text">
                                            Upload images
                                        </div>
                                    </div>
                                </div>
                            </div>

1 Answers1

1

You need to use Jquery onchange event when the file is selected read the file using FileReader

    $('#fileToUpload').on('change', function() {

        var file = this.files[0];
        var imagefile = file.type;
        var imageTypes = ["image/jpeg", "image/png", "image/jpg", "image/gif"];
        if (imageTypes.indexOf(imagefile) == -1) {
            //display error
            return false;
            $(this).empty();
        }
        else {
            var reader = new FileReader();
            reader.onload = function(e) {
                $(".empty-text").html('<img src="' + e.target.result + '"  />');
            };
            reader.readAsDataURL(this.files[0]);
        }

    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<input class="upload_file" type="file" name="fileToUpload" id="fileToUpload">


 <div class="item-images clearfix">
                                        <div class="empty-text">
                                            Upload images
                                        </div>
                                    </div>
Masivuye Cokile
  • 4,723
  • 3
  • 16
  • 33