2016-09-28 101 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; 
 
?>