Facebook graph api: upload multipart/form-data encoded image - image

I am trying to post an image using the source parameter (Multipart/form-data) in the Graph API explorer. My source parameter looks like this:
{Content-Type: multipart/form-data; boundary=xxxsrixxx
--xxxsrixxx
Content-Disposition: attachment; filename=try2.gif
Content-Type: image/gif
Content-Transfer-Encoding: binary,base64
R0lGODlhXgExAYeAAQAAAAEBAQICAgMDAwQEBAUFBQYGBgcHBwgICAkJCQoKCgsLCwwMDA0NDQ4ODg8PDxAQEBERERISEhMTExQUFBUVFRYWFhcXFxgYGBkZGRoaGhsbGxwcHB0dHR4eHh8fHyAgICEhISIiIiMjIyQkJCUlJSYmJicnJygoKCkpKSoqKisrKywsLC0tLS4uLi8vLzAwMDExMTIyMjMzMzQ0NDU1NTY2Njc3Nzg4ODk5OTo6Ojs7Ozw8PD09PT4+Pj8/P0BAQEFBQUJCQkNDQ0REREVFRUZGRkdHR0hISElJSUpKSktLS0xMTE1NTU5OTk9PT1BQUFFRUVJSUlNTU1RUVFVVVVZWVldXV1hYWFlZWVpaWltbW1xcXF1dXV5eXl9fX2BgYGFhYWJiYmNjY2RkZGVlZWZmZmdnZ2hoaGlpaWpqamtra2xsbG1tbW5ubm9vb3BwcHFxcXJycnNzc3R0dHV1dXZ2dnd3d3h4eHl5eXp6ent7e3x8fH19fX5+fn9/fzL/oICAgIGBgYKCgoODg4SEhIWFhYaGhoeHh4iIiImJiYqKiouLi4yMjI2NjY6Ojo+Pj5CQkJGRkZKSkpOTk5SUlJWVlZaWlpeXl5iYmJmZmZqampubm5ycnJ2dnZ6enp+fn6CgoKGhoaKioqOjo6SkpKWlpaampqenp6ioqKmpqaqqqqurq6ysrK2tra6urq+vr7CwsLGxsbKysrOzs7S0tLW1tba2tre3t7i4uLm5ubq6uru7u7y8vL29vb6+vr+/v8DAwMHBwcLCwsPDw8TExMXFxcbGxsfHx8jIyMnJycrKysvLy8zMzM3Nzc7Ozs/Pz9DQ0NHR0dLS0tPT09TU1NXV1dbW1tfX19jY2NnZ2dra2tvb29z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ZRbGXjPHh6QIFRuAEnCHGVpGYS8GrBiMGffAFbtAGTbCtiUxY1RIAZSCPlTECquAMXRAIuNAHiHDRSxEH/AIDMkMqVe0YSTgsALguBtECu6YtuvopRXDh1XJQVI4Q1mAHfzAECtAApPcAKCAGoU11XxFpldGvvRGnX94RYIIIwHCrXD4szzvn/VHcfG4d7vK1fy4feeI96NqB48OSn4ZeHgSVLku06OwhLyMH6eZR6JQOHdd06evh55oeHJze6bpRLlYhqqD+Heq8I3ta6uUhDC1wA6H5kKq+HoLAARKACLaQDDDwMLG+67ze677+68Ae7MI+7MRe7MZ+7Mie7Mq+7Mze7M7+7NAe7dKOKAAAIf8LUElBTllHSUYxLjAWSW1hZ2UgZnJvbSBjbGlwYm9hcmQBIAA7
--xxxsrixxx--}
This always seems to return
{
"error": {
"message": "(#324) Requires upload file",
"type": "OAuthException",
"code": 324
}
}
Few questions:
Does facebook source parameter accept base64 encoded image data?
Has anyone tried using the source parameter in the graph api explorer and have a working sample?
should the source param value should be url-encoded?
Note: My access token has all the required permissions and if i am not wrong, my encoding seems to be wrong. The base64 encoded text above is a complete image and i could decode it and get the image.

Ok. This is going to sound crazy. After a week of trying I was able to post an image successfully to the facebook wall. The fix was to send the raw binary data as it is (no base64 encoding - fb does not like it) and make sure your multipart/form-data is correct. For instance, if you boundary is defined as "boundary=--xxxsrixxx" your actual request should look like this "----xxxsrixxx\r\nContent-Disposition......\r\n----xxxsrixxx"

This works fine for me, it only uses native JavaScript features and a file input:
const fileReader = new FileReader();
const file = document.getElementById('imageInput').files[0];
fileReader.onloadend = async () => {
const photoData = new Blob([fileReader.result], {type: 'image/jpg'});
const formData = new FormData();
formData.append('access_token', pageAccessToken);
formData.append('source', photoData);
formData.append('message', 'some status message');
let response = await fetch(`https://graph.facebook.com/${pageId}/photos`, {
body: formData,
method: 'post'
});
response = await response.json();
console.log(response);
};
fileReader.readAsArrayBuffer(file);
More information: http://www.devils-heaven.com/facebook-javascript-sdk-photo-upload-with-formdata/

Related

Postgraphile StatusCode: 405, ReasonPhrase: 'Method Not Allowed

I use Postgraphile locally and it work very well.
I want to send a HttpClient post requset in my Application, but it does not work and I get this error:
StatusCode: 405, ReasonPhrase: 'Method Not Allowed
hier is my code:
using (HttpClient httpClient = new HttpClient())
{
string content = "query {accounts {nodes {id,name,street,postalcode,city}}}";
var httpConent = new StringContent(content, Encoding.UTF8, "application/json");
var responseMessage = await httpClient.PostAsync("http://localhost:5000/graphiql", httpConent);
var result = responseMessage.Content.ReadAsStringAsync();
}
In line 5 of your code snippet, you're submitting to the /graphiql URL (which is for the GraphiQL GUI), you should be submitting to /graphql.
In line 4 of your snippet, you are claiming the content variable is application/json, but it is in fact a GraphQL string. You should be submitting something like {"query":"{__typename}"} as application/json.
You do not appear to be issuing an Accept: application/json header.
I suggest you use the network debugging tools of your web browser to inspect exactly what the browser is doing when it runs the GraphQL query, and compare that with what you are attempting to do with your code. You might also refer to the GraphQL-over-HTTP specification: https://graphql.github.io/graphql-over-http/draft/

Handling base64 string as application/pdf for a single endpoint on API Gateway

We have an API that has multiple different endpoints, as you'd expect. We have the requirement to add a new endpoint which will return an application/pdf along with the file data.
To do this, we return the following:
return {
statusCode: 200,
headers: {
'Content-Type': 'application/pdf',
'Content-disposition': `attachment; filename=${filename}.pdf`,
'Accept': 'application/pdf',
},
body: fileData,
isBase64Encoded: true,
};
The isBase64Encoded only works when a binary media type is set in the API Gateway. As detailed here:
https://medium.com/#ngchiwang/aws-api-gateway-lambda-return-binary-image-ba8faa660839
The issue we have is that by setting the binary media type to * / * (no spaces) on the API Gateway, this, in turn, affects all other endpoints on the API.
Example This breaks one endpoint on the OPTIONS cors check, returning an InternalServerErrorException without reason. This endpoint is just a GET with no data in the request.
Does this mean we need a separate API just for this one endpoint, or is there a way we can include this in the same APIG?
For further clarification, this is a POST that includes a small amount of JSON in the request: {"someValue":1234} and returns the above application/pdf content type.
I'm just tackling this issue and resolved it like this:
Send base 64 string just as normal json response and handle the pdf part on the client
const sendRes = (status:number, body:any) => {
var response = { statusCode: status, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
return response;
};
return sendRes(201, {pdf:your-base64-string} );
Then on the client (Nuxt in my case):
let res = await this.$store.dispatch('pdf/makePdf')
const linkSource = `data:application/pdf;base64,${res.data.pdf}`;
const downloadLink = document.createElement("a");
const fileName = "your-pdf-filename.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
This open a download window and lets you save the file locally

Malformed request from aiohttp.ClientSession().post() with multiple image files

I'm still relatively new to Python and my first time to use aiohttp so I'm hoping someone can help spot where my problem is.
I have a function that does the following:
retrieves from the JSON payload two base64 strings - base64Front and base64Back
decode them, save to "images" folder
send the Front.jpg and Back.jpg to an external API
this external API expects a multipart/form-data
imgDataF = base64.b64decode(base64FrontStr)
frontFilename = 'images/Front.jpg'
with open(frontFilename, 'wb') as frontImgFile:
frontImgFile.write(imgDataF)
imgDataB = base64.b64decode(base64BackStr)
backFilename = 'images/Back.jpg'
with open(backFilename, 'wb') as backImgFile:
backImgFile.write(imgDataB)
headers = {
'Content-Type': 'multipart/form-data',
'AccountAccessKey': 'some-access-key',
'SecretToken': 'some-secret-token'
}
url = 'https://external-api/2.0/AuthenticateDoc'
files = [('file', open('./images/Front.jpg', 'rb')),
('file', open('./images/Back.jpg', 'rb'))]
async with aiohttp.ClientSession() as session:
async with session.post(url, data=files, headers=headers) as resp:
print(resp.status)
print(await resp .json())
The response I'm getting is status code 400 with:
{'ErrorCode': 1040, 'ErrorMessage': 'Malformed/Invalid Request detected'}
If I call the url via Postman and send the two jpg files, I get status code 200.
Hope someone can help here.
Thanks in advance.
Try using FormData to construct your request. Remove the content type from header and use it in FormData field as below:
data = FormData()
data.add_field('file',
open('Front.jpg', 'rb'),
filename='Front.jpg',
content_type='multipart/form-data')
await session.post(url, data=data)
Reference: https://docs.aiohttp.org/en/stable/client_quickstart.html#post-a-multipart-encoded-file

Saving a ZIP File from AJAX Response in Angular 2/TypeScript

I am trying to download a zip fie which is returned as binary in the response of a AJAX Request.
I tried the following code but was not able to download it and even if I downloaded it the file got corrupted. I checked whether the response is correct and went to the network tab in developer tool and saved the response as a zip file and opened it, and it was successfully opened.
Hopefully someone can tell me what I am doing wrong.
var URL = window.URL;
var downloadData = new Blob([data._body], { type: 'application/octet-stream' });
var downloadURL = URL.createObjectURL(downloadData);
window.open(downloadURL);
the browser openes up a new window and tells me the file is not supported in IE & downloads a corrupted file in Chrome. The URL in browser is something like
blob:http://localhost:4200/62b8283c-1391-4133-98a4-ed3cc9aa1f73
-
var downloadData = new Blob([data._body], { type: 'application/zip' });
FileSaver.saveAs(downloadData,"hi.zip");
The above code does not give any specific errors but when the file is saved it is corrupted.
I also tried the above code with type as application/octet-stream but that has the same result.
Thing is the binary data seems to be perfectly fine, the only thing I need to do is open a save dialog which will save the binary data. Seems to be a pretty simple usecase, but seems to be a bit confusing in case of zip in the Js/TS side.
I think the main issue is that I am creating a blob with the binary data(which I don't think I need to or should be transforming to a blob) but I was not able to trigger the download without creating a blob object as the APIs seem to be accepting only blob(like the URL Object or FileSaver API).
I had the exact same problem, the zip file was corrupt when I was trying to open it.
I fixed it by adding: responseType = ResponseContentType.ArrayBuffer
Here is my code:
public httpRequest(call) {
call.headers = new Headers({
'Authorization': 'Bearer ' + localStorage.getItem('id_token'),
'Content-Type': 'application/json',
'Accept': 'application/octet-stream'
});
let req = new Request(call);
req.responseType = ResponseContentType.ArrayBuffer;
return this.http.request(req).map((res: Response) => {
return res;
});
}
make sure you imported:
import { Http, Headers, Request, Response, BaseResponseOptions, ResponseContentType } from '#angular/http';

using img templats with ngSrc sends text/html instead of image/gif when data array is loaded via $http

I have a template like this:
<img class="picto"
ng-repeat="module in modules"
ng-src="{{module.Source}}"
title="{{module.Title}}"
ng-click="module.handler();"/>
When I set the $scope.modules array using static code, everything works fine, and the images are fetched via GET using media type "image/gif" (for gif files). However, when I retrieve the same array using $http.get() - see the code below -, angular tries to retrieve the images using media type "text/html" which results in an 404 error:
$http.get('/api/modules', {})
.success(function (data) {
$http.defaults.get = { 'Content-Type': 'image/gif' }; // apparently useless
$scope.modules = data;
for (var module in $scope.modules) {
$scope.modules[module].handler = function () { alert(this.Id); };
}
delete $http.defaults.get; // ...useless
});
Trying to add a header default did not help either (// apparently useless). Can you see what's wrong?
Try it with Accept: 'image/gif' instead of Content-Type: 'image/gif'.
The Content-Type header describes the data format you are sending to the server. The Accept header describes the data formats you accept in response from the server.

Resources