2016-09-28 32 views
0

因此,我試圖製作一個表單將圖像上傳到服務器中的數據庫和文件夾。我無法弄清楚如何使用javascript將圖像數據發送到PHP文件。通過Javascript將圖像數據傳遞給PHP

我有以下的Javascript:

function FeedPost() { 
    $('#FeedResults').show(); 
    document.getElementById('FeedResults').innerHTML = '<center><img src="img/Loading.gif" title="Loading" /></center>';  
    var post_text = document.getElementById('PostText').value; 
    var file = document.getElementById('PostImage').files[0]; 
    var file_name = file.name; 
    var file_size = file.size; 
    var file_type = file.type; 
    var dataString = 'feed='+post_text+'&img_name='+file_name+'&img_size='+file_size+'&img_type='+file_type; 
     $.ajax({ 
     type: "GET", 
     url: "post_feed.php?"+dataString, 
     dataType: "json", 
     success: function(data) { 
     for (var i in data) { 
      var entry = data[i]; 
      var success = entry.results.success; 
      var message = entry.results.message; 
     } 
     document.getElementById('FeedResults').innerHTML = '<div class="ResultsText">'+message+'</div>'; 
    } 
});   
} 

在PHP我刪除了$ _FILE []編碼,以確保該文件變量在PHP中,他們所經歷的一切。

這裏的PHP代碼:

<?php 
$feed_message = strip_tags(mysql_real_escape_string($_GET['feed'])); 
$img_name = strip_tags(mysql_real_escape_string($_GET['img_name'])); 
$img_size = strip_tags(mysql_real_escape_string($_GET['img_size'])); 
$img_type = strip_tags(mysql_real_escape_string($_GET['img_type'])); 
$folder="img/uploads/"; 
// new file size in KB 
$new_size = $img_size/1024; 
// new file size in KB 

// make file name in lower case 
$new_file_name = strtolower($img_name); 
// make file name in lower case 
$final_file=str_replace(' ','-',$new_file_name); 

$img_output = $final_file.''.$img_type; 
// Checking post Variables 
if($img_size == 0) { 
    if(strlen($feed_message) < 3) { 
     $message = 'Post Too Short'; 
     $results = ['success' => false, 'message' => $message]; 
    } 
    else { 
     $message = 'Post Successful!'; 
     $results = ['success' => true, 'message' => $message]; 
     $insert = mysql_query("INSERT INTO feed(user,message,img,time) values ('$id','$feed_message','NULL','".time()."')"); 
    } 
} 
// Post has an image attached 
else { 
    if(strlen($feed_message) < 3) { 
     $message = 'Post Too Short'; 
     $results = ['success' => false, 'message' => $message]; 
    } 
    else { 
     move_uploaded_file($final_file,$folder); 
     $insert = mysql_query("INSERT INTO feed (user,message,img) values ('$id','$feed_message','$img_output','".time()."')"); 
     $message = 'Image Posted!'; 
     $results = ['success' => true, 'message' => $message]; 
    } 
} 
$data[] = ['results' => $results]; 
echo json_encode($data); 
?> 

輸出網址是:post_feed.php飼料=測試.... & img_name =奇才-Khalifa.jpg & img_size = 271330 & img_type =圖像/ JPEG

而且PHP輸出如下:[{ 「結果」:{ 「成功」:真實的, 「消息」: 「圖像發佈!」}}]

添加HTML:

  <form action="javascript:void;" method="post" enctype="multipart/form-data"> 
       <input type="text" id="PostText" placeholder="Message" /> 
       <input type="file" name="file" id="PostImage" /> 
       <input type="submit" value="Submit" class="LoginButton" onClick="FeedPost()" /> 
       <input type="reset" value="Reset" class="LoginButton" /> 
      </form> 
+1

警告的mysql_query,mysql_fetch_array,的mysql_connect等擴展在PHP 5.5.0被棄用,並且它是在PHP 7.0.0中刪除。相反,應該使用MySQLi或PDO_MySQL擴展。 – Melchizedek

+1

@Glide謝謝你幫我解決這個問題。我已經知道,我很想學習MySQLi的功能,但是我全職工作,沒有足夠的時間來完成這項工作。 –

+0

上傳時使用tmp_name而不是img_name – Beginner

回答

0

只需添加到您的JS這個文件

var formData = new FormData(); 
formData.append('file', file); // append file to your form 


// add this to your ajax request parameters to pass the image file 
data: formData, // add this to your parameters in your ajax request 

你的js會是這樣

function FeedPost() { 
    $('#FeedResults').show(); 
    document.getElementById('FeedResults').innerHTML = '<center><img src="img/Loading.gif" title="Loading" /></center>';  
    var post_text = document.getElementById('PostText').value; 
    var file = document.getElementById('PostImage').files[0]; 


    // you just add this 
    var formData = new FormData(); 
    formData.append('file', file); // append file to your form 


    var file_name = file.name; 
    var file_size = file.size; 
    var file_type = file.type; 
    var dataString = 'feed='+post_text+'&img_name='+file_name+'&img_size='+file_size+'&img_type='+file_type; 
     $.ajax({ 
     type: "GET", 
     url: "post_feed.php?"+dataString, 
     data: formData, // add this to your parameters in your ajax request 
     dataType: "json", 
     success: function(data) { 
     for (var i in data) { 
      var entry = data[i]; 
      var success = entry.results.success; 
      var message = entry.results.message; 
     } 
     document.getElementById('FeedResults').innerHTML = '<div class="ResultsText">'+message+'</div>'; 
    } 
});   
} 

在你的PHP文件

更改

move_uploaded_file($final_file,$folder); 

move_uploaded_file($_FILES['file']['tmp_name'], $folder.'/' . $final_file); 
+0

只是告訴我,如果你有任何錯誤,如果你嘗試var_dump($ _ FILES);在你的php文件中調試文件 – Beginner

+0

嘿,我得到了這個錯誤代碼:TypeError:'append'在一個沒有實現接口FormData的對象上調用。 –

+0

你可以截圖你的js代碼 – Beginner

0

我正在爲您測試解決方案。它通過ajax測試了post_feed.php的連接,它保存了文件並對服務器端的變量進行了必要的驗證。

我沒有測試的唯一的事情是mysql_query函數 - 我的意思是,實際上證明它將圖像保存到數據庫,只允許查詢與修改後的變量。一旦您測試了通過ajax的連接實際工作並且文件正在保存img/uploads /文件夾,則將$ is_postInsertedWithImage = true和$ is_postInsertedWithoutImage = true的行註釋到真實的mysql_query。

我組織了一點點代碼。 javascript通過AJAX連接成功的php文件,在文件夾中上傳圖像並將響應返回給index.html。

有一件事,請閱讀評論我讓你在代碼中,因爲有些事情我會更好地理解,比如記住檢查文件夾的權限,以及上傳的文件夾的權限,還請注意一些細節,如變量$ id,你在你的mysql_query中使用,並沒有顯示在你的代碼中,並且它將需要測試查詢,我給你一個$ userId = 4作爲一種你可以測試或取消註釋的部分來訪問它通過會話。我希望它能幫助你。快樂的代碼!

<script type="text/javascript"> 
 
    \t function FeedPost() { 
 

 
\t \t  var element = document.getElementById('FeedResults'); 
 

 
\t \t  element.innerHTML += '<center><img src="img/Loading.gif" title="Loading" /></center>';  
 

 
\t \t  var post = document.getElementById('postText').value; 
 
\t \t  var file = document.getElementById("postImage").files[0]; \t \t  
 

 
\t \t  var xhr = new XMLHttpRequest(); 
 
\t \t  var formdata = new FormData(); 
 

 

 
\t \t  if(file !== undefined){ 
 
\t \t  \t formdata.append("file1", file); \t \t \t \t  \t 
 
\t \t  } \t 
 
\t \t  formdata.append("post", post); 
 

 

 
\t \t  xhr.open("POST", "post_feed.php"); 
 
\t \t  xhr.send(formdata); \t 
 

 
\t \t \t xhr.onreadystatechange = function(){ 
 
\t \t \t \t if(this.readyState === 4 && this.status === 200){ 
 

 
\t \t \t \t \t eval("var response = (" + this.responseText + ")"); 
 
\t \t \t \t \t 
 
\t \t \t \t \t // Check out the message response from the upload in the Browser Console 
 
\t \t \t \t \t // before test the database. It should work fine. 
 
\t \t \t \t \t console.log(response.message); \t \t \t \t \t \t 
 
\t \t \t \t \t 
 

 
\t \t \t \t \t // element.innerHTML += response.message; 
 
\t \t \t \t \t // document.body.appendChild(element); 
 
\t \t \t \t \t alert(response.message); 
 
\t \t \t \t } 
 
\t \t \t } \t \t \t \t  
 
\t \t } \t \t 
 
    </script>

<?php 
 

 
//Get the post feed 
 
$postFeed = $_POST['post']; 
 

 
//Lets check the post if is not ok we send a response and save memory 
 
//there is no need to store any other variable or chech the image 
 
if (strlen($postFeed) < 3) { 
 
    
 
    $jsonMessage = json_encode(array(
 
     'message' => 'Your post is too short! It MUST have more than 3 characters' 
 
    )); 
 
    
 
    echo $jsonMessage; 
 
    // Run out 
 
    exit(); 
 
} 
 

 
// Where is your user ID stored?? I didn't see in the example 
 
// session?? Cookie? Get it here in the PHP file not in the index.html Remember that!. 
 
// For security reasons. Don't use global too. 
 
// I just put a fixed value, 4, to the id to test purposes; 
 

 
// example: session_start(); 
 
//$userId = $_SESSION['current_user_id'] 
 
$userId = 4; 
 

 
//Get the file name 
 
$fileName = $_FILES['file1']['name']; 
 

 
//Get the size of the file to verification 
 
$fileSize = $_FILES['file1']['size']; 
 

 
//Get the type of file : image 
 
$fileType = $_FILES['file1']['type']; 
 

 
//Store errors in the file 
 
$fileErrMsg = $_FILES['file1']['error']; 
 

 
//Temporary file 
 
$fileTmp = $_FILES['file1']['tmp_name']; 
 

 
//Raises a flag if an error is found when uploading or with the image 
 
$error_flag = 0; 
 

 

 
//Path to upload the file. 
 
//My /img/ folder is placed where my php script runs 
 
//Change to your folder 
 
//IMPORTANT: Give file permission to write, ex: sudo chmod 777 /img/uploads or better use chmod go+w /img/uploads/ 
 

 
// change to your folder: 
 
// $pathToUpload = dirname(__FILE__)."/img/uploads/"; 
 
$pathToUpload = dirname(__FILE__) . "/img/"; 
 

 
// The name of the file to Upload cleaned 
 
$cleanFileNameToUpload = str_replace(' ', '-', strtolower($fileName)); 
 

 
// Store the message we want to use in the Ajax Call 
 
$responseMessage = array(); 
 

 
//Check if it was uploaded an image use isset() 
 
if (isset($fileName)) { 
 
    if (!$fileTmp || $fileErrMsg > 0) { 
 
     $responseMessage[] = 'An error ocurred when uploading!'; 
 
     $error_flag  = 1; 
 
     
 
    } elseif ($fileSize > 500000) { 
 
     
 
     $responseMessage[] = 'File is bigger than 500kb!'; 
 
     $error_flag  = 1; 
 
     
 
    } else { 
 
     
 
     if (move_uploaded_file($fileTmp, $pathToUpload . $fileName)) { 
 
      $responseMessage['message'] = 'Yeah Babe! File Upload now let just save to database and we are done!'; 
 
      
 
      // Now we store in the database 
 
      // in future try to learn mysqli or even Oriented Object aproach like PDO - it's really worth and also best practices - it's really easy to learn. \t \t \t \t 
 
      
 
      // For test - replace for the line below to test save the database. 
 
      $is_postInsertedWithImage = true; 
 
      
 
      //$is_postInsertedWithImage = mysql_query("INSERT INTO feed (user,message,img) values ('$userId','$postFeed','$cleanFileNameToUpload','".time()."')"); 
 
      
 
      if ($is_postInsertedWithImage) { 
 
       $responseMessage['message'] = 'Post with image inserted correctly!'; 
 
      } else { 
 
       $responseMessage['message'] = 'There was an error saving the post in the database!'; 
 
      } 
 
      
 
     } else { 
 
      $responseMessage['message'] = 'It was not posible to write image in the folder. Check Permissions and Upload folder location!'; 
 
     } 
 
    } 
 
    
 
} else { 
 
    // If there is no image save only the image \t 
 
    $is_postInserted = true; 
 
    
 
    // $is_postInserted = mysql_query("INSERT INTO feed(user,message,img,time) values ('$userId','$postFeed','NULL','".time()."')"); \t 
 
    
 
    if ($is_postInserted) { 
 
     $responseMessage['message'] = 'Post without image inserted correctly!'; 
 
    } else { 
 
     $responseMessage['message'] = 'There was an error saving the post without image in the database!'; 
 
    } 
 
} 
 

 
$jsonMessage = json_encode($responseMessage); 
 
echo $jsonMessage; 
 
?>