keditor convert blob generated image URL to base64 - javascript

I'm using keditor for my document. My problem here is that the images are generated as blob and I have no way of knowing where they are being stored thus when converting the file to another format the images are lost.
Sample image tag with blob:
<img src="blob:http://localhost/7b0e82ab-445b-4866-b8b5-09b4881a0544" width="100%" height="" style="display: inline-block;">
I was hoping I can find a way to convert this to blob either using PHP or JS.
I also found this post but no solution was provided:
JS convert blob url to Base64 file

Somewhere in your code you have a reference to the blob that you had to get your blob url, take it an pass it to the FileReader like so:
// Just an example file
var blob = new Blob(['abc'], {type: 'text/plain'})
var reader = new FileReader()
reader.onload = function() {
var base64data = reader.result
console.log(base64data)
}
reader.readAsDataURL(blob)

Using AJAX:
$.ajax({
method: "GET",
url: "blob:http://127.0.0.1:8000/e89c5d87-a634-4540-974c-30dc476825cc",
dataType: "binary",
}).done(function( data ) {
var reader = new FileReader();
reader.readAsDataURL(data);
reader.onloadend = function() {
var base64data = reader.result;
console.log(base64data)
}
});
Have not tested this, but should point you in the right direction though.

Related

Excel binary data to fileReader

I have a binary string (from an REST API) that is the content of a Excel file.
PK\x03\x04\x14\x00\x06\00\x00\x00���N�0\x10E�H�C�-#\b5��\x12*Q>�ēƪc[�ii����\x10B�\x15j7�\x12��{2��h�nm���ƻR\f����U^\x1B7/���%�\x17\x19�rZY�\x14\x1B#1\x19__�f�\x00�q��R4D�AJ�\x1Ah\x15\x16>����V\x11�ƹ\f�Z�9����NV ...
What I want is to put this content in a FileReader object. I tried to convert the content to blob and to use readAsBinaryString but it doesn't work.
Maybe I missed something
However, when I use an input type=file, it's works with this example
$("#input").on("change", (e) => {
selectedFile = e.target.files[0];
});
let fileReader = new FileReader();
fileReader.readAsBinaryString(selectedFile);
fileReader.onload = (event)=>{
let data = event.target.result;
let workbook = XLSX.read(data,{type:"binary"});
}
What I would like is for selectedFile to reflect the binary string and not have to go through an input type=file
Thanks for your help
You can create a Blob object from the binary string, then create a File object from the Blob and finally, create a FileReader object from the File object.
var binaryString = "PK\x03\x04\x14\x00\x06\00\x00\x00���N�0\x10E�H�C�-#\b5��\x12*Q>�ēƪc[�ii����\x10B�\x15j7�\x12��{2��h�nm���ƻR\f����U^\x1B7/���%�\x17\x19�rZY�\x14\x1B#1\x19__�f�\x00�q��R4D�AJ�\x1Ah\x15\x16>����V\x11�ƹ\f�Z�9����NV ...";
// create a Blob object
var blob = new Blob([binaryString], { type: "application/vnd.ms-excel" });
// create a File object from the Blob
var file = new File([blob], "file.xlsx");
// create a FileReader object
var reader = new FileReader();
// use the readAsArrayBuffer method to read the file
reader.readAsArrayBuffer(file);
// when the reading is done, log the result
reader.onloadend = function () {
console.log(reader.result);
};

how do I append readAsBinaryString or readAsDataURL to FormData

I have this normal file upload, but what do I need is to send a file stored as a string in local storage along with FormData, because I cannot change anything on server. I will store the file locally using readAsBinaryString or readAsDataURL .
var reader = new FileReader();
/**
File reading code
reader.readAsBinaryString(file);
**/
var fileString = reader.result
I need to send fileString into below formData.append instead of the imagefile.files[0]
Any idea?
var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})

How to convert BLOB to image using python

I need to send an image from client to server using blob
I have converted a image to BLOB in jquery (client side) and sending the blob to python flask (server side) the problem is, I can't recreate image from BLOB. I have tried the following code in python but failed to get the image
Jquery code to convert image to blob:
function changeFile() {
var file = this.files[0];
var reader = new FileReader();
reader.addEventListener('load', readFile);
reader.readAsText(file);
}
function readFile(event) {
document.body.textContent = event.target.result;
console.log(event.target.result);
appendFileAndSubmit(event.target.result);
}
function appendFileAndSubmit(imageUrl){
var ImageURL = imageUrl
var data = {
'logo':ImageURL
}
$.ajax({
url: 'http://sdsdss/User/imgBlob',
method: 'POST',
dataType : 'json',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8'
}).done(function(response){
var datas = JSON.parse(response);
console.log(datas);
});
}
document.getElementById("inp").addEventListener("change", changeFile);
Python Code: To recreate BLOB to image
function getImage(self):
reqData = json.loads(request.data)
Logo = reqData['logo']
png_recovered = base64.decodestring(Logo)
f = open("temp.png", "w")
f.write(png_recovered)
f.close()
Don't read the file as text, You are dealing with binary data. Best way to transfer binary with json is if you read the file as base64 instead reader.readAsDataURL(file) This will encode all bytes to a web safe base64 string (no slash or plus). Then you have to decode it with python as well.
I discourage you from using json when dealing with file transfer as it will increase the bandwidth with ~3 times as much (not to mention the time it also takes to decode and encode it back and forth) For this I recommend you instead use FormData.
var fd = new FormData()
fd.append('logo', files[0])
$.ajax({
url: 'http://sdsdss/User/imgBlob',
method: 'POST',
data: fd,
// Setting false prevent jQuery from transforming the data
processData: false,
contentType: false
}).then(function(response) {
console.log(JSON.parse(response))
})
or simpler yet, just post the file without any formdata, json or extra fields if they are not necessary.
fetch(uploudUrl, { method 'PUT', body: this.files[0] })

How to convert node.js array-buffer to javascript array buffer

I send audio to client using node.js :
res.send(audio); / audio it is the buffer array
And I get object 'arrayBuffer' in data.
And I conver it to Blob and after to file (I want to get dataURL to show it in player)
.then(
(result) => {
result.arrayBuffer().then(function (data) {
const blob = new Blob([data], { type: 'audio/wav' });
var fileReader = new FileReader();
fileReader.readAsDataURL(blob);
fileReader.onload = function (evt) {
// Read out file contents as a Data URL
var url = evt.target.result;
res({blob, url})
};
})
}
)
And it works good. I use this url it as src of my <audio> attribute and it works.
But now I want to send this file from server as a part of json. Now I get audioBuffer from the serve in "audio" property. I chage arrayBuffer method to json in fetch:
result.json().then(function (data) {
const blob = new Blob([data.audio], { type: 'audio/wav' });
...
But now it doesn't work. I tried to use module www.npmjs.com/package/to-array-buffer to convert data.audio to js-arrayBuffer, but it doesn't help.
Maybe you know what's problem here?
Ok, I solved problem. I use module about whick I wrote to-array-buffer, but I use not toArrayBuffer(data.audio) but toArrayBuffer(data.audio.data)

turn image binary data into img tag

When i do a post request to a route i have
/generate/image
i get something like: var file =
����JFIF��C��C��� ��
�����+�}Yϭ�F39M>���������>���;��ˋ��uXʽ�w�ڤx\-[2g��k�S���H���m
[�V?[_W����#��v��}6�[��F�F�%����n�...
in the client i do:
var blob = new Blob([file], {type: 'image/png'});
var reader = new FileReader();
reader.onload = function (e) {
$('#result').attr('src', e.target.result);
};
reader.readAsDataURL(blob);
but i get a corrupt image
what can i do?
EDIT:
if i do
img.src = 'data:image/png;base64,' + btoa(file);
i get:
Uncaught InvalidCharacterError: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
Please don't use base64 and wast bandwidth + CPU
Send the image binary as is and handle them correctly with Ajax.
You should not get the result as a string. set xhr responseType to blob or use fetch's blob method.
fetch("/generate/image").then(res => res.blob())
When you have the blob don't use the file reader to turn it to a url.
Use URL.createObjectURL(blob)
At your backend you can do following:
var fs = require('fs');
fs.readFile(path to image from you file, 'base64', function(err, buf){
/* Here you can send your base64 image data to client. Your base64 data is in buf.
I am using socket. You can just send. Read more about readFile function*/
socket.emit('image upload', { image: true, buffer: buf });
});
As my client receives data from socket, I call a function:
socket.on('image upload', function(data){
displayImage(data);
});
var displayImage = function(data){
var URL = 'data:image/jpg;base64,'+data.buffer;
document.querySelector('#img-id').src = URL;
};
The image will then be showed in img tag.
Hope this works for you.

Categories