2015-02-23 74 views
0

我目前有一個麻煩插入文件輸入(圖像)到我的數據庫,但它返回我空值,當我試圖將其插入數據庫,其他文本輸入已成功插入數據庫,但圖像除外。無法插入圖像到數據庫與ajax序列化函數

這裏是我的Ajax代碼,我用做AJAX功能:

$("#testing").confirm({ 
        confirm: function (el) { 
         $.ajax({ 
          url: 'bannerItem.php', 
          data: el.closest('form').serialize(), 
          type: 'post' 

         }).done(function() { 
          if(!alert('Banner Had Successfully Updated.')){document.getElementById('form').reset();} 
         }).fail(function() { 
          //if the post is failed show an error message if you want 
          alert('Some error occur. Please try again later.'); 
         }).always(function() { 
          //this is executed on success and failure 
          $('#myhiddendiv').hide(); 
         }) 
        } 
       }); 

這裏是PHP代碼:

<?php 
    include 'dbConnection.php'; 

    global $dbLink; 


     $target_file = basename($_FILES['uploaded_file']['name']); 
     $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 
     //Check image file type 


      // Make sure the file was sent without errors 
      if($_FILES['uploaded_file']['error'] == 0) { 

       //Gather all required data 
       $item_id = $dbLink->real_escape_string($_POST['banner_id']); 
       $name = $dbLink->real_escape_string($_POST['bannerName']); 
       $data = $dbLink->real_escape_string(file_get_contents($_FILES['uploaded_file']['tmp_name'])); 



       //Create the SQL query 
       $query = "INSERT INTO banner_item (banner_item_id, banner_name,banner_data,banner_created) VALUES ('{$item_id}','{$name}','{$data}', NOW() 
        )"; 

       //Execute the query 
       $result = $dbLink->query($query); 

       //Check if it was successfull 
       if($result) { 

        echo 'Name : '.$name.'</br>'; 
        echo 'Result : Success! Your file was successfully added!'; 
       } 
       else{ 
        echo 'Result : Error! Failed to insert the file' 
         . "<pre>{$dbLink->error}</pre>"; 
       } 
      } 
      else { 
       echo'An error accured while thefile was being uploaded. ' 
        . 'Error code: '. intval($_FILES['uploaded_file']['error']); 
      } 


     // Close the mysql connection 
     $dbLink->close(); 


    // Echo a link back to the main page 
    echo '<p>Click <a href="index.html">here</a> to go back</p>'; 
    ?> 

如果我使用的PHP代碼withouth的Ajax的功能,一切可以插入到數據庫中,但是當我使用ajax函數時,只有圖像無法插入到數據庫中。

這裏是我用來提交價值形態:

<form id="form" action="bannerItem.php" method="POST" enctype="multipart/form-data"> 
            <div class="box-body"> 
             <input type="hidden" name="banner_id" value="1"></input> 
             <div class="form-group" > 
              <label for="bannerName">Banner Name 旗幟名稱</label> 
              <input type="text" class="form-control" name="bannerName" id="bannerName" placeholder="Please Enter Name" onChange="checkDisabled(testing);"> 
             </div> 
             <div class="form-group"> 
              <label for="exampleInputFile">File input</label> 
              <input type="file" id="uploaded_file" name="uploaded_file" onChange="checkDisabled(testing);"><br> 
              <p class="help-block">Your picture size not more than 2MB. (Only JPEG/JPG/PNG is allowed)</p> 
             </div> 

             <div class="checkbox"> 
              <button id="testing" type="submit" class="btn btn-primary" disabled>Update</button>  
             </div> 
            </div><!-- /.box-body --> 


           </form>     <!-- D 

我一直在尋找周圍小時如何在計算器解決這個和谷歌,大多使用XHR2或FORMDATA但我我不確定使用哪一個以及如何將它用於我的代碼,因爲我仍然是一個使用AJAX和PHP函數的新人。如果我在我的Ajax代碼上犯了任何錯誤,請引導我。謝謝你,祝你有美好的一天:)

回答

0

你不能通過窗體序列化來上傳文件。如果你的瀏覽器的要求是在IE9可以使用XHR上傳或FileAPI插件

例子:

function startUpload() { 
    var fileInput = document.getElementById("fileInput"); 

    if (fileInput.files.length == 0) { 
     alert("Please choose a file"); 
     return; 
    } 

    var progressBar = document.getElementById("progressBar"); 
    var xhr = new XMLHttpRequest(); 

    xhr.upload.onprogress = function(e) { 
     var percentComplete = (e.loaded/e.total) * 100; 
     progressBar.value = percentComplete; 
    }; 

    xhr.onload = function() { 
     if (xhr.status == 200) { 
      alert("Sucess! Upload completed"); 
     } else { 
      alert("Error! Upload failed"); 
     } 
    }; 
    xhr.onerror = function() { 
     alert("Error! Upload failed. Can not connect to server."); 
    }; 

    progressBar.value = 0; 
    xhr.open("POST", "ajax-upload", true); 
    xhr.setRequestHeader("Content-Type", fileInput.files[0].type); 
    xhr.send(fileInput.files[0]); 
} 

更多信息HERE

+0

您好,感謝給建議使用XHR2,但我仍然有一個文本文件要與圖像一起插入,我該如何做到這一點?謝謝 – 2015-02-23 07:46:48

+0

只需使用FileAPI插件即可。我認爲你可以指定可用的擴展名來上傳。 https://github.com/mailru/FileAPI 順便說一句,如果你使用AngularJS我可以幫你一個指令。 – Kosmog 2015-02-23 07:57:00

0

我解決我的表單數據功能的問題。我知道FireAPI和XHR2可以完成,但對於像我這樣的初學者更簡單的理解,我認爲這是解決我的問題的解決方案。謝謝,我希望我能用我的示例代碼來幫助其他人。 :)

這裏是我成功地用在我的AJAX代碼: //文件和文字上傳與FORMDATA功能

  $("form#form").submit(function(){ 
      var formData = new FormData($(this)[0]); 

      $.ajax({ 
       url:'bannerItem.php', 
       type: 'POST', 
       data: formData, 
       async: false, 
       success: function (data) { 
        if(!alert('Banner Had Successfully Updated.')){location.reload();} 
       }, 
       cache: false, 
       contentType: false, 
       processData: false 
      }); 

      return false; 
     });