Facebook Javascript Form Data Photo Upload: requires upload file error - javascript

I've searched nearly every thread for 15-some hours and haven't found an answer to my problem. I'm using strictly Javascript to upload a photo to Facebook using form data. I decoded the base64 data from my JPEG image (originally svg -> canvas element), using this decode method (https://github.com/danguer/blog-examples/blob/master/js/base64-binary.js) and then converting it to a string in the form data format like https://gist.github.com/andyburke/1498758 (not using XMLHttpRequest). I then put that string as the "source" parameter in the post. I keep getting a "(#324) Requires upload file". It works perfectly if I just put in a url for the image. Can anybody help? Thanks!
// The function to post the image:
FB.api("/me/photos",
"POST",
{
"source": window.image_source,
"message": "...",
"fileName": "..."
},
function(response) {
console.log(response.error);
}
});
// How I got the image_source:
var img = canvas.toDataURL("image/jpeg");
var encoded = img.substring(img.indexOf(',')+1,img.length);
var decoded = decode(encoded);
convertToFormData(decoded);
function convertToFormData(imageData) {
var boundary = 'myboundary';
var formData = "Content-Type: multipart/form-data; boundary=" + boundary + '\r\n\r\n';
formData += '--' + boundary + '\r\n';
formData += 'Content-Disposition: form-data; name="source"; filename="' + "myfile" + '"\r\n';
for ( var i = 0; i < imageData.length; ++i )
formData += String.fromCharCode(imageData[i] & 0xff);
formData += '\r\n';
formData += '--' + boundary + '\r\n'+ 'Content-Disposition: form-data; name="message"\r\n\r\n';
formData += "Description" + '\r\n';
formData += '--' + boundary + '--\r\n';
window.image_source = formData;
}
function decode(input) {
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var lkey1 = keyStr.indexOf(input.charAt(input.length-1));
var lkey2 = keyStr.indexOf(input.charAt(input.length-2));
var bytes = (input.length/4) * 3;
if (lkey1 == 64) bytes--;
if (lkey2 == 64) bytes--;
var chr1, chr2, chr3; var enc1, enc2, enc3, enc4;
var i = 0;var j = 0;
var uarray = new Uint8Array(bytes);
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
for (i=0; i<bytes; i+=3) {
enc1 = keyStr.indexOf(input.charAt(j++));
enc2 = keyStr.indexOf(input.charAt(j++));
enc3 = keyStr.indexOf(input.charAt(j++));
enc4 = keyStr.indexOf(input.charAt(j++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
uarray[i] = chr1;
if (enc3 != 64) uarray[i+1] = chr2;
if (enc4 != 64) uarray[i+2] = chr3;
}
return uarray;
}

You have to turn the Canvas Image into a Blob to upload it to Facebook:
const dataURItoBlob = (dataURI) => {
let byteString = atob(dataURI.split(',')[1]);
let ab = new ArrayBuffer(byteString.length);
let ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {
type: 'image/jpeg'
});
}
After that, you can use the blog with FormData:
formData.append('source', blob);
Source: http://www.devils-heaven.com/facebook-javascript-sdk-photo-upload-from-canvas/

Related

blob in multipart/form-data sending as [object Blob] with XMLHttpRequest

I have a binary file I want to send in a multipart/form-data POST request. I want to include the binary in my javascript so I found a javascript function to convert a base64 string to a blob, it is below.
var b64data = 'blablabla';
const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return blob;
}
const contentType = 'application/x-gzip';
const payload = b64toBlob(b64data, contentType);
I then use that blob as part of a multipart/form-data send with XMLHttpRequest. The relevant code is:
function fileUpload(url, fileData, fileName, nameVar, ctype) {
var fileSize = fileData.length,
boundary = "ABCDEFGHIFD",
xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "multipart/form-data, boundary="+boundary);
var body = "--" + boundary + "\r\n";
body += 'Content-Disposition: form-data; name="' + nameVar +'"; filename="' + fileName + '"\r\n';
body += "Content-Type: " + ctype + "\r\n\r\n";
//body += fileData;
end = "\r\n--" + boundary + "--";
//var body = fileData;
xhr.send(body + fileData + end);
return true;
}
When I feed payload into the function like fileUpload(url,payload,fileName,nameVar,ctype);, the part that should be binary data just transfers as [object Blob]. If I take out the body and only send the fileData,
var body = fileData;
xhr.send(body);
It transfers the binary data in the packet.
Why is the first function not sending the binary through?

JSON to excel file in javascript

I am using the following code to create excel file data from JSON object and then download it on the click of a button.
getExcelFile: function() {
testJson = validation_data;
testTypes = {
"name": "String",
"city": "String",
"country": "String",
"birthdate": "String",
"amount": "Number"
};
emitXmlHeader = function() {
return '<?xml version="1.0"?>\n' +
'<ss:Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">\n' +
'<ss:Worksheet ss:Name="Sheet1">\n' +
'<ss:Table>\n\n';
};
emitXmlFooter = function() {
return '\n</ss:Table>\n' +
'</ss:Worksheet>\n' +
'</ss:Workbook>\n';
};
jsonToSsXml = function(jsonObject) {
var row;
var col;
var xml;
var data = typeof jsonObject != "object"
? JSON.parse(jsonObject)
: jsonObject;
xml = emitXmlHeader();
for (row = 0; row < data.length; row++) {
xml += '<ss:Row>\n';
for (col in data[row]) {
xml += ' <ss:Cell>\n';
xml += ' <ss:Data ss:Type="' + testTypes[col] + '">';
xml += data[row][col] + '</ss:Data>\n';
xml += ' </ss:Cell>\n';
}
xml += '</ss:Row>\n';
}
xml += emitXmlFooter();
return xml;
};
download = function(content, filename, contentType) {
if (!contentType)
contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
var a = document.getElementById('test');
var blob = new Blob([content], {
'type': contentType
});
a.href = window.URL.createObjectURL(blob);
a.download = filename;
};
download(jsonToSsXml(testJson), 'validation_data.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
}
But the file created doesn't open in Microsoft Office 2007 and gives the error 'File may be corrupt'. Please help.
I recently got a solution for this question using AlaSQL.
Their working example.
var sheet_1_data = [{Col_One:1, Col_Two:11}, {Col_One:2, Col_Two:22}];
var sheet_2_data = [{Col_One:10, Col_Two:110}, {Col_One:20, Col_Two:220}];
var opts = [{sheetid:'Sheet One',header:true},{sheetid:'Sheet Two',header:false}];
var res = alasql('SELECT * INTO XLSX("sample_file.xlsx",?) FROM ?', [opts,[sheet_1_data ,sheet_2_data]]);
Libraries required:
<script src="http://alasql.org/console/alasql.min.js"></script>
<script src="http://alasql.org/console/xlsx.core.min.js"></script>
NOTE: Don't pass undefined values to the function. Generated file will produce warning messages if you try to open them in this case.
Other options were able to convert JSON to CSV (not XLSX).

Ajax login portal - how do I automate authentication using a webpage/iframe?

I have been able to accomplish this using Selenium and Python, this is not a viable solution as this must be purely web based(meaning any computer can go to the website and using a known user/password configure the device automatically)
When I try to use '[https://user:password#ipaddress]' it gives me a SSL error:
Unable to make a secure connection to the server. This may be a problem with the server, or it may be requiring a client authentication certificate that you don't have.
Error code: ERR_SSL_PROTOCOL_ERROR
My hope is that loading the devices web page in an iframe will allow me to use javascript to interact with the devices web interface(login & send form data).
Here is the login.js that is used by the device:
function submitLoginInfo() {
$("#notemsg").html("");
var authHeader = encodeBase64($("input:radio:checked").attr("value") + ":" + $("input[name='password']").attr("value"));
$.ajax({
type: "GET",
url: "auth.htm?t=" + new Date().toGMTString(),
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + authHeader);
},
success: function(result) {
document.cookie = "Authorization=Basic " + authHeader;
window.location = "/index.htm";
},
error: function(request,err,e){
$("#notemsg").html("<span style='color: red'>Invalid password. Please try again.</span>");
$("input[name='password']").attr("value", "");
document.login.password.focus();
},
complete: function(request, textStatus) {
}
});
}
function resetLoginInfo() {
$(".loginField").attr("value", "");
document.login.password.focus();
$("#notemsg").html("");
}
encodeBase64 = function (input) {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var result = '';
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
do {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
result += chars.charAt(enc1) + chars.charAt(enc2) + chars.charAt(enc3) + chars.charAt(enc4);
} while (i < input.length);
return result;
};
function removeCookie() {
document.cookie = "Authorization=; expires=" + new Date().toGMTString();
}

Upload Base64 Image Facebook Graph API

I'm trying to upload a base64 image to a FaceBook page using Node.js. I have managed to get the upload working with all the multipart data etc should I read the file from the filesystem (ie. using fs.readFileSync('c:\a.jpg')
However, should I use the base64 encoded image and try upload it, it give me the following error : {"error":{"message":"(#1) An unknown error occurred","type":"OAuthException","code":1}}
I have tried converting it to binary by new Buffer(b64string, 'base64'); and uploading that, but no luck.
I have been struggling with this for 3 days now, so anyhelp would be greatly appreciated.
Edit : If anyone also knows how I could convert the base64 to binary and successfully upload it, that would also work for me.
Edit : Code Snippet
var postDetails = separator + newlineConstant + 'Content-Disposition: form-data;name="access_token"' + newlineConstant + newlineConstant + accessToken + newlineConstant + separator;
postDetails = postDetails + newlineConstant + 'Content-Disposition: form-data; name="message"' + newlineConstant + newlineConstant + message + newlineConstant;
//Add the Image information
var fileDetailsString = '';
var index = 0;
var multipartBody = new Buffer(0);
images.forEach(function (currentImage) {
fileDetailsString = fileDetailsString + separator + newlineConstant + 'Content-Disposition: file; name="source"; filename="Image' + index + '"' + newlineConstant + 'Content-Type: image/jpeg' + newlineConstant + newlineConstant;
index++;
multipartBody = Buffer.concat([multipartBody, new Buffer(fileDetailsString), currentImage]); //This is what I would use if Bianry data was passed in
currentImage = new Buffer (currentImage.toString('base64'), 'base64'); // The following lines are what I would use for base64 image being passed in (The appropriate lines would be enabled/disabled if I was using Binary/base64)
multipartBody = Buffer.concat([multipartBody, new Buffer(fileDetailsString), currentImage]);
});
multipartBody = Buffer.concat([new Buffer(postDetails), multipartBody, new Buffer(footer)]);
I hope this will be useful. By doing photo upload to FB only with the help of javascript you can use the following method. Required thing here are imageData(which is base64 format of image) and the mime type.
try {
blob = dataURItoBlob(imageData,mimeType);
} catch (e) {
console.log(e);
}
var fd = new FormData();
fd.append("access_token",accessToken);
fd.append("source", blob);
fd.append("message","Kiss");
try {
$.ajax({
url:"https://graph.facebook.com/" + <<userID received on getting user details>> + "/photos?access_token=" + <<user accessToken>>,
type:"POST",
data:fd,
processData:false,
contentType:false,
cache:false,
success:function(data){
console.log("success " + data);
},
error:function(shr,status,data){
console.log("error " + data + " Status " + shr.status);
},
complete:function(){
console.log("Ajax Complete");
}
});
} catch(e) {
console.log(e);
}
function dataURItoBlob(dataURI,mime) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs
var byteString = window.atob(dataURI);
// separate out the mime component
// write the bytes of the string to an ArrayBuffer
//var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
var blob = new Blob([ia], { type: mime });
return blob;
}
//EDIT AJAX SYNTAX
The code above didn't quite work for me (Missing comma after type:"POST", and data URI to blob function reported errors. I got the following code to work in Firefox and Chrome:
function PostImageToFacebook(authToken)
{
var canvas = document.getElementById("c");
var imageData = canvas.toDataURL("image/png");
try {
blob = dataURItoBlob(imageData);
}
catch(e) {
console.log(e);
}
var fd = new FormData();
fd.append("access_token",authToken);
fd.append("source", blob);
fd.append("message","Photo Text");
try {
$.ajax({
url:"https://graph.facebook.com/me/photos?access_token=" + authToken,
type:"POST",
data:fd,
processData:false,
contentType:false,
cache:false,
success:function(data){
console.log("success " + data);
},
error:function(shr,status,data){
console.log("error " + data + " Status " + shr.status);
},
complete:function(){
console.log("Posted to facebook");
}
});
}
catch(e) {
console.log(e);
}
}
function dataURItoBlob(dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], { type: 'image/png' });
}
Here's the code at GitHub
https://github.com/DanBrown180/html5-canvas-post-to-facebook-base64
Dan's Answer works the best. Something else that might be helpful in this scenario is the optional argument for posting photos: 'no_story'. This arg defaults to true forcing the photo-post to skip the user's wall. By adding
fd.append("no_story", false);
you can update the user's wall with the photo-post.
I would have just left this as a comment but... 50 Rep for comments.
We can simplify image recoding by usage of the modern Fetch API instead of Uint8Array.
var url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
fetch(url)
.then(res => res.blob())
.then(blob => console.log(blob))`
I did something very similar to your question. I had a webcam-snapshot that needed to be POSTed to a Facebook Fan Page.
The setup was in a restaurant where people could take a picture and it would be posted onto the Restaurants Page. People would then see a QR code to the posted facebook-photo which they could choose to share on their own profile.
Hope this can help somebody because I searched a lot to get to this working SOLUTION
Note: My image is BASE64 encoded already.
//imageData is a base64 encoded JPG
function postSocial(imageData, message){
var ia = toUInt8Array(imageData);
postImageToFacebook(mAccessTokenPage, "imageName", "image/jpeg",ia, message);
}
function toUInt8Array(dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs
var byteString = window.atob(dataURI);
// write the bytes of the string to an ArrayBuffer
//var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return ia;
}
function postImageToFacebook( authToken, filename, mimeType, imageData, message ) {
// this is the multipart/form-data boundary we'll use
var boundary = '----ThisIsTheBoundary1234567890';
// let's encode our image file, which is contained in the var
var formData = '--' + boundary + '\r\n'
formData += 'Content-Disposition: form-data; name="source"; filename="' + filename + '"\r\n';
formData += 'Content-Type: ' + mimeType + '\r\n\r\n';
for ( var i = 0; i < imageData.length; ++i )
{
formData += String.fromCharCode( imageData[ i ] & 0xff );
}
formData += '\r\n';
formData += '--' + boundary + '\r\n';
formData += 'Content-Disposition: form-data; name="message"\r\n\r\n';
formData += message + '\r\n'
formData += '--' + boundary + '--\r\n';
var xhr = new XMLHttpRequest();
xhr.open( 'POST', https://graph.facebook.com/ + {PAGE_ID} + "/photos?access_token=" + authToken, true );
xhr.onload = function() {
// ... Fill in your own
//Image was posted
console.log(xhr.responseText);
};
xhr.onerror = function(){
console.log("Error while sending the image to Facebook");
};
xhr.setRequestHeader( "Content-Type", "multipart/form-data; boundary=" + boundary );
xhr.sendAsBinary( formData );
}
Here is how I was able to post an image to facebook using the facebook JS API.
I am using the canvas HTML5 functionality. It's not fully supported by every browser.
You need first to get the image data. Then to encapsulate it in a form data.
I then use the FB.login API in order to retrieve the access token and the userID.
var data = $('#map >> canvas').toDataURL('image/png');
var blob;
try {
var byteString = atob(data.split(',')[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
blob = new Blob([ab], {type: 'image/png'});
} catch (e) {
console.log(e);
}
var fd = new FormData();
fd.append("source", blob);
fd.append("message", "Photo Text");
FB.login(function(){
var auth = FB.getAuthResponse();
$.ajax({
url:"https://graph.facebook.com/"+auth.userID+"/photos?access_token=" + auth.accessToken,
type:"POST",
data:fd,
processData:false,
contentType:false,
cache:false,
success:function(data){
console.log("success " + data);
},
error:function(shr,status,data){
console.log("error " + data + " Status " + shr.status);
},
complete:function(){
console.log("Ajax Complete");
}
});
}, {scope: 'publish_actions'});
Here is an example that does not need jQuery or other libraries, just the native Fetch API:
const dataURItoBlob = (dataURI) => {
let byteString = atob(dataURI.split(',')[1]);
let ab = new ArrayBuffer(byteString.length);
let ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {
type: 'image/jpeg'
});
}
const upload = async (response) => {
let canvas = document.getElementById('canvas');
let dataURL = canvas.toDataURL('image/jpeg', 1.0);
let blob = dataURItoBlob(dataURL);
let formData = new FormData();
formData.append('access_token', response.authResponse.accessToken);
formData.append('source', blob);
let responseFB = await fetch(`https://graph.facebook.com/me/photos`, {
body: formData,
method: 'post'
});
responseFB = await responseFB.json();
console.log(responseFB);
};
document.getElementById('upload').addEventListener('click', () => {
FB.login((response) => {
//TODO check if user is logged in and authorized publish_actions
upload(response);
}, {scope: 'publish_actions'})
})
Source: http://www.devils-heaven.com/facebook-javascript-sdk-photo-upload-from-canvas/

Why does the following Javascript not work on Firefox 12, but works in IE9?

I have a simple code fragment which does Base64 decoding on the contents of a textbox when a button is clicked on.
When loaded in IE9, it works exactly as expected, but in Firefox 12, clicking on the button doesn't do anything.
The code is here:
<html>
<head>
<script type="text/javascript">
var keyStr = "ABCDEFGHIJKLMNOP" +
"QRSTUVWXYZabcdef" +
"ghijklmnopqrstuv" +
"wxyz0123456789+/" +
"=";
function decode64(input) {
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
var base64test = /[^A-Za-z0-9\+\/\=]/g;
if (base64test.exec(input)) {
alert("There were invalid base64 characters in the input text.\n" +
"Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
"Expect errors in decoding.");
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
do {
enc1 = keyStr.indexOf(input.charAt(i++));
enc2 = keyStr.indexOf(input.charAt(i++));
enc3 = keyStr.indexOf(input.charAt(i++));
enc4 = keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return unescape(output);
}
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
function decodeHtml(){
var contentdiv = document.getElementById("html");
var targetdiv = document.getElementById("target");
targetdiv.innerHTML = decode64(contentdiv.innerHTML.trim());
}
</script>
</head>
<body>
<textarea id="html">
</textarea>
<button onClick="decodeHtml()">Decode</button><br><br>
<div id="target"></div>
</body>
</html>
Shouldn't the last line:
targetdiv.innerHTML = decode64(contentdiv.innerHTML.trim());
be:
targetdiv.innerHTML = decode64(contentdiv.value.trim());
jsFiddle example.

Categories

Resources