[英]Facebook Graph API how to upload image in node.js?
I am trying to follow this guide:我正在尝试遵循本指南:
https://developers.facebook.com/docs/graph-api/resumable-upload-api https://developers.facebook.com/docs/graph-api/resumable-upload-api
After researching how to attach multipart/form-data, as is suggested in the guide I came up with this code:在研究了如何附加 multipart/form-data 之后,正如指南中所建议的,我想出了这个代码:
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
}
I want to be getting the uploaded file handle, but all Im getting in the response is a huge object, that starts like this (with statusCode 200):我想获得上传的文件句柄,但我在响应中得到的都是一个巨大的对象,它以这样的方式开始(状态代码为 200):
IncomingMessage {
_readableState: ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,
flowing: null, ...
What am I doing wrong?我究竟做错了什么? Probably the way I am attaching the file.
可能是我附加文件的方式。 The guide doesnt state which name to give it, so I just named it "file".
该指南没有说明给它起什么名字,所以我只是把它命名为“文件”。
Any help is greatly appreciated.任何帮助是极大的赞赏。
I figured it out, although its probably not optimal:我想通了,虽然它可能不是最佳的:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.