dream5694 2019-03-07 06:35
浏览 104

如何在没有刷新页面的情况下上传(和可视化)图像?

Could you tell me how i can upload and visualization images without refresh page in php like this picture(for example):

enter image description here

When I click on "+" i can upload the image,and the image is being visualized at the moment(without refresh page). 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>

And div class when the images will be show:

<script type="text/template" id="tpl-product-image">
    <div class="col-sm-6 col-md-4 item-thumb" data-idx="{{fileId}}">
        <div class="image-holder thumbnail">
            <div class="preview">
                <img src="{{fileUrl}}" />
            </div>
            <div class="caption clearfix">
                <label class="pull-left">
                    {{#is_main}}
                    <input type="checkbox" class="uniform check-main" data-idx="{{fileId}}" checked />
                    {{/is_main}}
                    {{^is_main}}
                    <input type="checkbox" class="uniform check-main" data-idx="{{fileId}}" />
                    {{/is_main}}
                     Заглавна
                </label>
                <button class="remove-image btn btn-white pull-right" data-idx="{{fileId}}">
                    <i class="glyphicon glyphicon-trash"></i>
                </button>
            </div>
        </div>
    </div>
</script>

and JQUERY:

$('.upload_image').click(function() {
        $(".upload_file").trigger("click");    
    });
  • 写回答

2条回答 默认 最新

  • douxuanpa8298 2019-03-07 06:52
    关注

    use change event, then get the file and send to PHP file like below

     $('#fileToUpload').on("change", function () {
            var file = $("#fileToUpload").prop("files")[0];
            var data = new FormData();
            data.append('fileName', file);
                });
                        $.ajax({
                        url: "urlPHPFILE",
                        type: "POST",
                        data: data,
                        dataType : 'json',
                        processData: false,
                        contentType: false,
                        cache: false,
                        success:function(data){
    
                        },
                        error:function(err){
                            console.error(err);
                        }
                    });
    

    php file

    $file = $_POST['fileName']
    

    after upload, if you want to do something you must use the success function

    in PHP file you must back Url patch image .and get in on success function.

    PHP file

    .
    .//If the file was successfully uploaded
     $status = array('status' => "success", "urlPatchImage" => $UrlPatch);
     return $status;
    .
    .
    .
    

    jquery code

    .
      success:function(data){
           var urlPatchImage = data.urlPatchImage;
      $("#image").attr("src", urlPatchImage );
     },
    .
    .
    

    html

    <img id="image" src="">
    
    评论

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像