Facebook Graph API如何在node.js上传图片



我正在努力遵循以下指南:

https://developers.facebook.com/docs/graph-api/resumable-upload-api

在研究了如何附加多部分/表单数据后,正如指南中所建议的那样,我想出了以下代码:

const FB = require("fb")
const fs = Npm.require("fs")
FB.setAccessToken(accesstoken)
const post = async () => {
let res = await FB.api("app/uploads", "post", {
file_type: "image/jpeg",
file_length: file_length,
})
if (!res || res.error) {
console.log(!res ? "error occurred" : res.error)
return
}
const http = require("http")
const FormData = require("form-data")
const form = new FormData()
const readStream = fs.createReadStream(imagepath)
form.append("file", readStream)
const req = http.request({
host: "graph.facebook.com",
headers: {
Authorization:
"OAuth accesstoken",
file_offset: 0,
Connection: "close",
...form.getHeaders(),
},
method: "POST",
path: "/" + res.id,
})
form.pipe(req, { end: true })
req.on("response", function (res) {
console.log(res)
})
return res
}

我想得到上传的文件句柄,但我在响应中得到的只是一个巨大的对象,它的开头是这样的(状态代码200(:

IncomingMessage {
_readableState: ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,
flowing: null, ...

我做错了什么?可能是我附加文件的方式。导游没有说明给它取哪个名字,所以我只是给它取了个名字"文件";。

非常感谢您的帮助。

我发现了它,尽管它可能不是最佳的:

const FB = require("fb")
const fs = Npm.require("fs")
FB.setAccessToken(accessToken)
let post = async () => {
let res = await FB.api("app/uploads", "post", {
file_type: "image/jpeg",
file_length: file_length,
})
if (!res || res.error) {
console.log(!res ? "error occurred" : res.error)
return
}

const request = require("request")
request.post({
url: "http://graph.facebook.com/" + res.id,
formData: {
source: {
value: fs.createReadStream(imagePath),
options: {
filename: filename,
contentType: "image/jpeg",
},
},
},
headers: {
Authorization:
"OAuth AccessToken",
file_offset: 0,
Connection: "close",
'content-type' : 'multipart/form-data'
}
},
function (err, resp, body) {
if (err) {
console.log("Error!")
} else {
console.log("URL: " + body)
}
})
return res
}
return post()

相关内容

  • 没有找到相关文章

最新更新