簡體   English   中英

使用 JSON 上傳圖像不起作用

[英]Uploading Image Using JSON is not Working

誰能幫助我的代碼結構? 它出什么問題了?

HTML

 <form method="post">
      <div class="col-md-4">              
        <div class="field name-box">
           <input class="btn" name="image_file" id="image_file" type="file" style="font-size:15px;width:100%;margin-bottom:2px;" required=""/>
        </div>
      </div>     
 </form>

JS

        var form_data = new FormData();

            $.ajax({
                type: "POST",
                url: baseUrlAction() + '?btn=add_product_image',
                data:  form_data,
                contentType: false,
                cache: false,
                processData:false,
                success: function(data){

                    alert("Successfully");

                },
                error: function(ts){
                }           
            });

AJAX_CONTROLLER

public function add_product_image(){

    if(is_array($_FILES)){
        if(is_uploaded_file($_FILES['image_file']['tmp_name'])){
            $sourcePath = $_FILES['image_file']['tmp_name'];
            $targetPath = "product_images/"."sample_img_name".".png";
            if(move_uploaded_file($sourcePath,$targetPath)){
                // echo '<script>alert("Successfully Save")</script>';
            }
        }
    }

}

但我一直想知道為什么我會在我的 ajax 表格上獲得success回復? 甚至我的upload_file也無法正常工作。 誰能幫我?

你需要在你的js文件中使用form_data append數據並發送響應

formData.append('image_file', $('#image_file')[0].files[0];);

            var form_data = new FormData();
            formData.append('image_file',  $('#image_file')[0].files[0]); 
            $.ajax({
                type: "POST",
                url: baseUrlAction() + '?btn=add_product_image',
                data:  form_data,
                contentType: false,
                cache: false,
                processData:false,
                success: function(data){

                    alert("Successfully");

                },
                error: function(){
                }           
            });

將表單元素傳遞給 FormData

let form = document.getElementById("yourFormId");
var form_data = new FormData(form);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM