如何在使用php,mysql上传之前预览图像

时间:2019-03-08 12:24:45

标签: javascript php jquery mysql ajax

我是一个初学者,还在学习编程。 我想做这样的事情: https://ufile.io/z2w0l 我的问题是在使用php,mysql上传到数据库之前,如何预览一些图像? 我有代码,但它的工作方式如下: 当我选择要上传的图像时,该图像不会显示。当我单击提交按钮时,图像正在显示。我将在此处为自己的布局拍照:https://prnt.sc/mv1ef0(这是我可以在其中上传图像的表单),https://prnt.sc/mv1erl(这是我的提交按钮“发布”)。当我单击“提交”按钮时,页面正在刷新并且图像正在显示(如这张照片):https://prnt.sc/mv1fjg 我想先预览图片:https://prnt.sc/mv1iiz(在此框中) 这是我的php代码:

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));
    }

这是我的HTML代码:

<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 个答案:

答案 0 :(得分:1)

选择文件后,您需要使用Jquery onchange事件,使用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>