javascript - 如何通过javascript SDK在facebook上上传照片

标签 javascript facebook facebook-graph-api

我只是想通过 Javascript SDK 将文件从计算机上传到 facebook,下面是我编写的用于在 facebook 上上传图像的代码,我有 Facebook javascript SDK 以及用于服务器端脚本的 PHP语言处理多部分表单数据以上传图像,但我完全不知道如何将图像作为 javascript Facebook SDK 的参数传递

	<script>
         // Wait until the DOM has loaded before querying the document

           var messageToPost;
		   $(document).ready(function(){

			          	var  isLoaded=false;
	  window.fbAsyncInit = function() {
        FB.init({
          appId      : '455772327890425',
          xfbml      : true,
          version    : 'v2.1'
        });
		
		isLoaded=true;
      };
	  
function checkIfLoaded() {
    if(isLoaded) console.log("LOADED!");
    else console.log("NOT YET!");

    return false;
  }
		
      (function(d, s, id){
         var js, fjs = d.getElementsByTagName(s)[0];
         if (d.getElementById(id)) {return;}
         js = d.createElement(s); js.id = id;
         js.src = "//connect.facebook.net/en_US/sdk.js";
         fjs.parentNode.insertBefore(js, fjs);
       }(document, 'script', 'facebook-jssdk'));
       
	   



			
            
			
			setTimeout(function(){alert('after set time out');login(); },2000);
			
			
			 
           
			
						
			
			function login()
			{
				console.log("login called");
               
               FB.login(function (response)
               {
                   accessToken = response.authResponse.accessToken;
                   console.log("inside real login");
               
                   if (response.authResponse) {
                       //fileUpload();
					  
                	  
					   postFB();
                       //Logout();          
                      //alert("Back to Login");
                	   }
                   
                   else {  alert("Login attempt failed!");}
               } , { scope: 'email,user_photos,photo_upload,publish_actions,publish_stream' });
               
			};
			
			function postFB()
			{
                 
                  //alert("message "+ messageToPost);
				  var images={}
				  
				   var wallPost = {
                                        message:      '<?php echo $messageToPost ?>',
                                        name        : 'SBIINTOUCH',
                                        description : 'SBIINTOUCH experience',
										height      : 70,
										width       : 60,
								        source     : '<?php   echo  (basename($_FILES["fileToUpload"]["name"])); ?>'
										
							          
                                  }; 
				   
				   
				   alert(wallPost['message'] +"\n"+wallPost['source'] );
				   
                 //posting in time line
                  FB.api('/me/photos', 'post', wallPost, function(response) {
                    if (!response || response.error) {
                      alert(JSON.stringify(response.error)+'Error occured while posting in personal feed');
                    } else {
                      alert('Post ID: personal feed ' + response.id);
                    }
                  });
                  
                 //posting in page
                  FB.api('/512538375541360/photos', 'post', 
                          wallPost, 
                      function(response) {

                          if (!response || response.error) {
                              alert(JSON.stringify(response.error)+ "while posting in page feed");
                          } else {
                              alert('Post ID : SBI Intouch ' + response.id);
                          }
                      });
				FB.logout();
			    };
			
             
			  
			
            
			});
			
			
			
			
			
			
			
	</script>
<!DOCTYPE html>
<html>
	<head>
	<script src="js/jquery-v1.js"></script>
		<script src="js/jquery-v1-8.js"></script>
        

	  </head>
	  <body>
       <div id="fb-root"></div>
       <script>
      
  
	   
	   </script>

	  <?php
	  echo $_POST['txta'];
	  echo $_POST['loc1'];
	  echo $_POST['Feedback'];
	   
	  
	  $target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	   //msg formation
				  $messageToPost = $_POST['txta'];
				 
                  $city          = $_POST['loc1'];
				   echo 	  'city  is '.$city;
				  
                  $sentiment= $_POST['Feedback'];
                 
                 if($sentiment==='Good')
               	  $messageToPost=$messageToPost." :) "."    #SBIInTouch".$city;
                 if($sentiment==='Neutral')
               	  $messageToPost=$messageToPost." :| "."    #SBIInTouch".$city;
                 if(  $sentiment==='Bad')  
               	  $messageToPost=$messageToPost." :( "."    #SBIInTouch".$city;
	  
      echo 	  'message is '.$messageToPost;
	  ?>

		 
		 
 
 
 
 
 
 
 
		
	</body>
</html>

最佳答案

嗯,我不太确定,但我得到了文档:3 https://developers.facebook.com/docs/graph-api/reference/v2.4/album/photos#publish

您可以直接发送图像字节,或使用 URL 让 Facebook 服务器加载它。 :)

使用js-sdk上传图像字节:

FB.api(
    "/{album-id}/photos",
    "POST",
    {
        "source": "{image-data}"
    },
    function (response) {
      if (response && !response.error) {
        /* handle the result */
      }
    }
);

或者,使用 url 而不是上传图像字节:

FB.api(
    "/{album-id}/photos",
    "POST",
    {
        "url": "{image-url}"
    },
    function (response) {
      if (response && !response.error) {
        /* handle the result */
      }
    }
);

关于javascript - 如何通过javascript SDK在facebook上上传照片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27764650/

相关文章:

iOS Facebook API/SDK 包装器?

ios - 收到错误 : Error Domain=com. facebook.sdk.core 代码=8 "(null)"

javascript - 来自node.js服务器端: photo upload to facebook

基于 iFrame 的 FB 页面应用程序上的 Facebook Like 按钮 - 问题

javascript - 将 css background-image : url(. ..) 替换为 <img> 标签并保持滚动效果

javascript - 如何从 iframe 中获取字段数据?

ios - Facebook iOS SDK 4.2 : Invalid URL Schemes for Multiple App Environments

Facebook Graph API - 通过一个查询访问评论和他们的回复

Javascript forEach - 如何循环一个对象?

javascript - 如何使用 DropDown Value onClick Button 跟踪动态 url - 为什么这不起作用?