假设您想要在纯JavaScript/JQuery中执行此操作 - 您需要使用iframe作为表单的目标,但有一点需要注意 - 您将无法使用返回数据(ID /呼叫成功),因为有相同的来源策略。
首先创建一个将持有该文件输入您想要设置任何其他变量的一种形式:
<form id="upload-photo-form">
<input name="source" id="source" size="27" type="file" />
<input name="message" id="message" type="text" value="message example please ignore" />
</form>
这里是使用的主要功能,创建一个iframe,分形式使用它,然后使用FQL从相册中检索最新的照片。
function fileUpload(form, action_url, div_id) {
// Create an iframe
var iframe = document.createElement("iframe");
iframe.setAttribute('id', "upload_iframe");
iframe.setAttribute('name', "upload_iframe");
iframe.setAttribute('width', "0px");
iframe.setAttribute('height', "0px");
iframe.setAttribute('border', "0");
iframe.setAttribute('style', "width: 0; height: 0; border: none;");
// Add to document.
form.parentNode.appendChild(iframe);
window.frames['upload_iframe'].name = "upload_iframe";
iframeId = document.getElementById("upload_iframe");
// Add event to detect when upload has finished
var eventHandler = function() {
if (iframeId.detachEvent)
{
iframeId.detachEvent("onload", eventHandler);
}
else
{
iframeId.removeEventListener("load", eventHandler, false);
}
setTimeout(function() {
try
{
$('#upload_iframe').remove();
} catch (e) {
}
}, 100);
FB.api({
method: 'fql.query',
query: 'SELECT src_big,pid,caption,object_id FROM photo WHERE aid= "' + albumID + '" ORDER BY created DESC LIMIT 1'
},
function(response) {
console.log(response);
}
);
}
if (iframeId.addEventListener)
iframeId.addEventListener('load', eventHandler, true);
if (iframeId.attachEvent)
iframeId.attachEvent('onload', eventHandler);
// Set properties of form...
form.setAttribute('target', 'upload_iframe');
form.setAttribute('action', action_url);
form.setAttribute('method', 'post');
form.setAttribute('enctype', 'multipart/form-data');
form.setAttribute('encoding', 'multipart/form-data');
// Submit the form...
form.submit();
}
在运行时,你可能会从以前的调用知道albumObjectID,并有从被登录或会话onauthchange返回的会话对象的访问令牌。
var url = 'https://graph.facebook.com/' + albumObjectID + '/photos?access_token=' + accessToken;
fileUpload($('#upload-photo-form')[0], url, $('#upload-photo-div')[0]);`
显然,这不是生产代码,有可以做,以提高它的可靠性(如检查的宽度,高度,标题提交图像的&标签的最新图像)的几件事情。在尝试上传之后检查&之前的最新图像等。
PS:注意albumObjectID与albumID,但它们不同,但两者都可以使用一些简单的FQL查询获得。 (例如:SELECT aid, object_id, can_upload, name FROM album WHERE owner = me() AND name = "My Album Name"
)
希望这会有所帮助。
CameraSchoolDropout
这里看我的答案,有简单,工作液 http://stackoverflow.com/问题/ 4999024/facebook-graph-api-upload-photo-using-javascript/8195849#8195849 – 2011-11-19 17:36:36
使用“url”insted的“来源” – sumitkanoje 2012-06-15 18:54:00