Base64 encode and image in Adobe Air - javascript

I am writing an Adobe Air app in HTML/JavaScript and I am trying to base64 encode an image so I can add it to and XML RPC request. I have tried many methods and nothing seems to work.
I see that actionscript has a Base64Encoder class that look like it would work, is there any way to utilize this in JavaScript?

Thanks #some for the link.
I used the btoa() function to base64 encode image data like this:
var loader = new air.URLLoader();
loader.dataFormat = air.URLLoaderDataFormat.BINARY;
loader.addEventListener(air.Event.COMPLETE,function(e){
var base64image = btoa(loader.data);
});
var req = new air.URLRequest('file://your_path_here');
loader.load(req);
I was trying to upload an image using metaWeblog.newMediaObject, but it turns out that the data doesn't need to be base64 encoded, so the binary value was all that was needed.

Related

How to convert/decode base64 from XHR request response string

I keep facing a problem converting XHR request response properly. I've read couple of solutions on Stackoverflow and on some other platforms but couldn't success to convert string to dataURL.
I've tried to convert string to through atob() and btoa() methods mention on MDN and this Stackoverflow post.
+ I've keep dive much to find a solution within lost of different methods but non of them took me aim.
How can I convert this response below to a dataURL properly to be able set the URL as image src?
XHR Request Response:
"�PNG
IHDR�� m"H3PLTE���������������������������������������������������?�U�iIDATx�흋�� Eۈ�Z����R�[���BB�]�_�Y�� x��a�a�a�a�a�a�a�a��-��nFI]]�}_x�}�����$ʆ�h�s�_4M_w�WI��*��.o���"��~۔�C^uڟ�P5W�'�[��(��}�=)���U�����Z�J#U��G�'�8G�߻ۓH�>��E���G�>݁K�ތ4l��C��
v�xu���?�*R��^������ł�B[�Y׸kkY����=�
l|H�s7Yp"���+6zV�cvSj+�
�}�c�c݄Pކ
~�W�N֨(�3����0[QƄ�Q�)o�_R,�]J����G�b��?��M 9� w*h��!=�%"�4������˔*a��
���6��w'��>��el3�e�l����c�ݍ(U.p�Q2�э����#��BɺB�h�4Sh��I�
�s��B���P735���(L�KU_�����s��v�]~�������6�+
/��iD��� �����uԏf�ﳽ�}nA�1_7��t�
+m�2W���P:�8�N�.Ԉ}�KQ�`�G0�P�Y�}�=A|�$� ��Xǭ�؅)w���>����m�J�R�֖��~}�n�#�G��7�ͽ���d������58C��i�6|�&�ۄ?pIl:P�l *FE�
q��wj��v��6�.�BQ�߁�����GBm�{�(�
�!f�k�Df*?}�+�N��"u��V,N��.eҚj��r�t��А�r��>)��*a��J����4�U���L��Z�/�ҵ���e=�;Qp����=x�[5=N��:8O}��k�?�Rr"�ma��tڱQ�I���R���=ܣU�MI�3Y�6\�~�v�.yJ�)��q�&���/�_�R�A-����{Ҡ�$��RNx%�}'�D�Tm�d9��}�n��~�kz��Ӝ���K� b��] L|�iqo3�O��p��l�� 'd�$�D�!:e��F=����'�"7g�F=b��7+Qܤ֩n�_"��c�����w$~`�V�"��I�{�&R̰G�O�|��%� ��/�L���>� �wb�S����- �3O����*J��7�͈�
�m�JL�Fdҗ��0��>���0��<����0�I!�33,y
d>3Ò�<y��)�'�pxS�E����;�����)�2�p��Dt��P�*�����Y�.�܈�
��D�5�Y�Ld����l��cb�lQ�|4�DED�͒�n
^3��&F!|��D��?�'��q
G�jN�h�\� 2ODVu�d���'���LLs_�ۏ�>CV� �gQ�{���e�
���2��*�Q�>|y��fg�M9a��E�IEND�B`�"
UPDATE:
I've succeed to render image through this post #
https://stackoverflow.com/a/8022521/7163711
Your XHR data is a png file, as expected. In order to show you how to embed it properly, I've taken the liberty of generating a "better" PNG - a 10x10 yellow square. it is base64-encoded in b64data on the first line of the snippet. The second line sets yourData as what you would have gotten from an XHR.
var b64data = "iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAFklEQVR42mP8/5/hDAMRgHFUIX0VAgBfZRvvtreybgAAAABJRU5ErkJggg==";
// Assuming your data is a raw PNG
var yourData = atob(b64data);
// We convert...
var btoa_data = btoa(yourData);
var elem = document.createElement("img");
elem.src = "data:image/png;base64,"+btoa_data;
document.getElementById("app").append(elem);
console.log(atob(b64data));
<div id="app"></div>
As you can see, btoa() works in order to base64-encode data; the only thing you need to do after this is to indicate in the src part of your img tag that:
It is a PNG (if it isn't, or if you are not sure if it will be, you'll need to check the first few bytes of your reply)
It is base64-encoded

How can we convert PDF of URL to Convert.ToBase64String in javascript

I have one URL which will ask Open/Save PDF when we browse it. I need to convert this pdf to Convert.ToBase64String in Javascript. I have one simple URL which have the PDF.
The URL is like
This
Let me know if you need anything else.
Define div to create the link inside it
<div id="getpdf">
<i>Generating PDF file, please wait..</i>
</div>
Then convert your PDF file containted in PDFAsString variable and create the inline datauri link like this to show this PDF inline:
// create base 64 encoded string
var PDFContentBase64 = btoa(unescape(encodeURIComponent(PDFAsString))));
var pdfdiv = document.getElementById("getpdf");`
pdfdiv.innerHTML = "<h3><a title=\"View PDF file\" href=\"data:application/pdf;base64,' + PDFContentBase64 + '\">Click here to VIEW PDF<\/a></h3>";`
UPDATE: (thanks to #roland) If you need to support IE8 and older browsers then consider N. Zackas's implementation of base64 encoding.

Decode Base64 encoded PDF content in browser

We transform HTML to PDF in the backend (PHP) using dompdf. The generated output from dompdf is Base64 encoded with
$output = $dompdf->output();
base64_encode($output);
This Base64 encoded content is saved as a file on the server. When we decode this file content like this:
cat /tmp/55acbaa9600f4 | base64 -D > test.pdf
we get a proper PDF file.
But when we transfer the Base64 content to the client as a string value inside a JSON object (the server provides a RESTful API...):
{
"file_data": "...the base64 string..."
}
And decode it with atob() and then create a Blob object to download the file later on, the PDF is always "empty"/broken.
$scope.downloadFileData = function(doc) {
DocumentService.getFileData(doc).then(function(data) {
var decodedFileData = atob(data.file_data);
var file = new Blob([decodedFileData], { type: doc.file_type });
saveAs(file, doc.title + '.' + doc.extension);
});
};
When we log the decoded content, it seems that the content is "broken", because several symbols are not the same as when we decode the content on the server using base64 -D.
When we encode/decode the content of simple text/plain documents, it's working as expected. But all binary (or not ASCII formats) are not working.
We have searched the web for many hours, but didn't find a solution for this that works for us. Does anyone have the same problem and can provide us with a working solution? Thanks in advance!
This is a example for a on the server Base64 encoded content of a PDF document:
JVBERi0xLjMKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZwovT3V0bGluZXMgMiAwIFIKL1BhZ2VzIDMgMCBS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DAwIG4gCjAwMDAwMDA0NzkgMDAwMDAgbiAKMDAwMDAwMDYxNiAwMDAwMCBuIAp0cmFpbGVyCjw8Ci9TaXplIDkKL1Jvb3QgMSAwIFIKL0luZm8gNSAwIFIKPj4Kc3RhcnR4cmVmCjcyNQolJUVPRgo=
If you atob() this, you don't get the same result as on the console with base64 -D. Why?
Your issue looks identical to the one I needed to solve recently.
Here is what worked for me:
const binaryImg = atob(base64String);
const length = binaryImg.length;
const arrayBuffer = new ArrayBuffer(length);
const uintArray = new Uint8Array(arrayBuffer);
for (let i = 0; i < length; i++) {
uintArray[i] = binaryImg.charCodeAt(i);
}
const fileBlob = new Blob([uintArray], { type: 'application/pdf' });
saveAs(fileBlob, 'filename.pdf');
It seems that only doing a base64 decode is not enough...you need to put the result into a Uint8Array. Otherwise, the pdf pages appear blank.
I found this solution here:
https://github.com/sayanee/angularjs-pdf/issues/110#issuecomment-579988190
You can use btoa() and atob() work in some browsers:
For Exa.
var enc = btoa("this is some text");
alert(enc);
alert(atob(enc));
To JSON and base64 are completely independent.
Here's a JSON stringifier/parser (and direct GitHub link).
Here's a base64 Q&A. Here's another one.

decoding a bin file to mp3 using Node Js

I am encoding a MP3 file to Base64 in Node Js using this method :
encodebase64 = function(mp3file){
var bitmap = fs.readFileSync(mp3file);
var encodedstring = new Buffer(bitmap).toString('base64');
fs.writeFileSync('encodedfile.bin', encodedstring);}
and then again I want to construct the MP3 file from the Base64 bin file, but the file created is missing some headers , so obviously there's a problem with the decoding.
the decoding function is :
decodebase64 = function(encodedfile){
var bitmap = fs.readFileSync(encodedfile);
var decodedString = new Buffer(bitmap, 'base64');
fs.writeFileSync('decodedfile.mp3', decodedString);}
I wondered if anyone can help
Thanks.
Perhaps it is an issue with the encoding parameter. See this answer for details. Try using utf8 when decoding to see if that makes a difference. What platforms are you running your code on?
#Noah mentioned an answer about base64 decoding using Buffers, but if you use the same code from the answer, and you try to create MP3 files with it, then they won't play and their file size will be larger than original ones just like you experienced in the beginning.
We should write the buffer directly to the mp3 file we want to create without converting it(the buffer) to an ASCII string:
// const buff = Buffer.from(audioContent, 'base64').toString('ascii'); // don't
const buff = Buffer.from(audioContent, 'base64');
fs.writeFileSync('test2.mp3', buff);
More info about fs.writeFile / fs.writeFileAsync

JPEG data obtained from FileReader doesn't match data in file

I'm trying to select a local JPEG file in the web browser via the HTML5 FileReader so I can submit it to a server without reloading the page. All the mechanics are working and I think I'm transferring and saving the exact data that JavaScript gave me, but the result is an invalid JPEG file on the server. Here's the basic code that demonstrates the problem:
<form name="add_photos">
​<input type=​"file" name=​"photo" id=​"photo" /><br />
​<input type=​"button" value=​"Upload" onclick=​"upload_photo()​;​" />​
</form>
<script type="text/javascript">
function upload_photo() {
file = document.add_photos.photo.files[0];
if (file) {
fileReader = new FileReader();
fileReader.onload = upload_photo_ready;
fileReader.readAsBinaryString(file);
}
}
function upload_photo_ready(event) {
data = event.target.result;
// alert(data);
URL = "submit.php";
ajax = new XMLHttpRequest();
ajax.open("POST", URL, 1);
ajax.setRequestHeader("Ajax-Request", "1");
ajax.send(data);
}
</script>
Then my PHP script does this:
$data = file_get_contents("php://input");
$filename = "test.jpg";
file_put_contents($filename, $data);
$result = imagecreatefromjpeg($filename);
That last line throws a PHP error "test.jpg is not a valid JPEG file." If I download the data back to my Mac and try to open it in Preview, Preview says the file "may be damaged or use a file format that Preview doesn’t recognize."
If I open both the original file on my desktop and the uploaded file on the server in text editors to inspect their contents, they are almost but not quite the same. The original file starts like this:
ˇÿˇ‡JFIFˇ˛;CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 90
But the uploaded file starts like this:
ÿØÿàJFIFÿþ;CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 90
Interestingly, if I view the data in a JavaScript alert with the commented-out line above, it looks just like the uploaded file's data, so it seems as if the FileReader isn't giving the correct data at the very beginning, as opposed to a problem that is introduced while transferring or saving the data on the server. Can anyone explain this?
I'm using Safari 6 and I also tried Firefox 14.
UPDATE: I just figured out that if I skip the FileReader code and change ajax.send(data) to ajax.send(file), the image is transferred and saved correctly on the server. So my problem is basically solved, but I'll award the answer points to anyone who can explain why my original approach with readAsBinaryString didn't work.
Your problem lies with readAsBinaryString. This will transfer the binary data byte-for-byte into a string, so that you will send a text string to your PHP file. Now a text string always has an encoding; and when you use XmlHttpRequest to upload a string, by default it will use UTF-8.
So each character, which was originally supposed to represent one byte, will be encoded as UTF-8... which uses multiple bytes for each character with a code point above 127!
Your best best is to use readAsArrayBuffer instead of readAsBinaryString. This will avoid all the character set conversions (that are necessary when dealing with strings).

Categories

Resources