I have a page to download a file from the Postgres database. Now I can hit the following URL to view the file content present in the database(stored as bytes)-HTTP://sandbox4.wootz.io:8080/api/blob/1/UploadFile/hope%20real.txt
Since the data is stored in a column of type bytes(byte array) when I click the download button it downloads the file and when I see its contents it is displayed as a byte array.
file.txt(contents)
[\x58595a5052415445454b3123473b4c534e44204e474f49574853474849444748445348474d70253335]
download functionality
axios({
url: 'api/store/blob/UploadFile/' + data.chosenfile,
method: 'GET',
headers: {'session_id': data.sessionid},
responseType: 'arraybuffer'
}).then(response => {
console.log(response.data); //displays nothing (empty)
var fileURL = window.URL.createObjectURL(new Blob([response.data]));
console.log('fileURL is'+fileURL)
var fileLink = document.createElement('a');
console.log('fileLink is'+fileLink)
fileLink.href = fileURL;
fileLink.setAttribute('download', data.chosenfile);
document.body.appendChild(fileLink);
fileLink.click();
)
console.log of the response object
{"data":{},"status":200,"statusText":"OK","headers":{"access-control-allow-origin":"*","connection":"keep-alive","content-length":"86","content-type":"text/html; charset=utf-8","date":"Mon, 06 Jul 2020 18:22:23 GMT","etag":"W/\"56-Vaz0hG1/FIgtEurgvK+wOU+4F4M\"","x-powered-by":"Express"},"config":{"url":"api/store/blob/UploadFile/hope real.txt","method":"get","headers":{"Accept":"application/json, text/plain, */*","Access-Control-Allow-Origin":"http://localhost","session_id":"c5b3b878-771e-4472-84eb-6de15686effa"},"transformRequest":[null],"transformResponse":[null],"timeout":0,"responseType":"arraybuffer","xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1},"request":{}}
Uploadfile part of my code(this is how the files was uploaded to database)
function readFileAsync(file) {
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onload = () => {
var base64Url = reader.result;
console.log(base64Url) //ENITRE BASE64 URL
resolve(base64Url.substr(base64Url.indexOf(',') + 1)); //will return only the base64string part from the base64 url
};
reader.onerror = reject;
reader.readAsDataURL(file);
})
}
async function uploadFile(path, data) {
try {
let base64string = await readFileAsync(data.chosenfile);
console.log('base64 content is'+ base64string)
let response = await axios({
method: 'post',
url: 'api/store/blob' + path,
headers: {'session_id': data.sessionid},
data: {"id":data.chosenfile.name, "file": base64string }
});
if (response.status == 200) {
console.log(response.status);
}
return response.data;
} catch (err) {
console.error(err);
}
}
what am i doing wrong? why am i getting the file contents as [\x58595a5052415445454b3123473b4c534e44204e474f49574853474849444748445348474d70253335] ? What should I do to get the actual file's content in the downloaded file?
NOTE:With respect to the upload part, I am using the same strategy for all kind of files(excel documents,txt files etc) which is encoding it to base64 encoded string before passing it in the axios post payload.Now this payload is passed to another project called data-manager (interacts with postgres database).so when this data-manager project recieves the payload that i sent, it converts it to bytes [] before inserting to the table column of type bytea.So ultimately when i download any file from this table i will get the file contents also in bytea format.
Your file is a correct ASCII text file with content [\x58595a5052415445454b3123473b4c534e44204e474f49574853474849444748445348474d70253335] literally.
That you get this content when you download it is perfectly fine, since it's what this file's content is.
What you want is to parse that content from the Hex representation they used to an actual ArrayBuffer to finally read that again as UTF-8 text (or any encoding respecting ASCII).
This has to be done after you do download the file and read it as text.
You first extract the actual bytes sequence as Hex from that [\x - ] wrapper, then you split the resulting string at every two chars to get hex values of every bytes, and finally you parse it into an Uint8Array to get back the original data:
// for StackSnippet we need to hardcode the response
// OP would have to make its request return that string
const response = { data: String.raw`[\x58595a5052415445454b3123473b4c534e44204e474f49574853474849444748445348474d70253335]` };
// .then( (response) => {
const encoded_text = response.data;
// remove leading "[\x" and final "]"
const encoded_data = encoded_text.slice( 3, -1 );
// split at every two chars, so we can get 0xNN, 0xNN
const hex_bytes = encoded_data.match( /.{2}/g );
// as numbers (0 - 255)
const num_bytes = hex_bytes.map( (hex) => parseInt( hex, 16 ) );
// wrap in an Uint8Array
const view = new Uint8Array( num_bytes );
// from there you can generate the Blob to save on disk
download( new Blob( [ view ] ), "file.txt" );
// but if you want to read it as UTF-8 text, you can:
const as_text = new TextDecoder().decode( view );
console.log( as_text );
// } );
function download( blob, filename ) {
const anchor = document.createElement( "a" );
anchor.href = URL.createObjectURL( blob );
anchor.download = filename;
anchor.textContent = "click to download";
document.body.append( anchor );
}
Related
I built a simple project using javascript and FastAPI. I would like to POST canvas image data in javascript to the server(FastAPI).
But, I get the 422 Unprocessable Entity error
# FastAPI
#app.post("/post")
async def upload_files(input_data: UploadFile = File(...)):
return JSONResponse(status_code = 200, content={'result' : 'success'})
// javascript
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
imageData = ctx.getImageData(0, 0, 112, 112);
fetch("http://{IP}/post", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
input_data: imageData,
}),
})
.then((response) => response.json())
here is my code. I am new one in javascript. so I don't know how can post data to server.
How can I do? Thanks in advance.
MatsLindh's way is correct but you can try upload image by formdata so you haven't convert to base64 then convert back to image
const dataURItoBlob = function(dataURI : string) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString : string;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
const url = canvas.toDataURL()
const file = dataURItoBlob(url)
//add file to formdata
const form = new FormData()
form.append('file', item.file)
//post this form in body
UploadFile expects a file being posted to the endpoint in the multipart/form-data format - i.e. as a regular POST with a bit of added metadata.
Since you're retrieving the image data and submitting it as JSON body, that won't match the expected format. You also want to use canvas.toDataURL() to convert the content to base64 before trying to submit it through your API to avoid any UTF-8 issues with JSON.
const pngData = canvas.toDataURL();
// then in your request:
body: JSON.stringify({
input_data: pngData,
}),
To handle this request change your view function signature to receive an input_data parameter (and use a better endpoint name than post):
#app.post("/images")
async def upload_files(input_data: str = Body(...)):
# check the expected format (content-type;<base64 content>)
# .. and decode it with base64.b64decode()
return {'content': input_data}
I am using react, Paparse and encoding-japanese
With Paparse I can upload a CSV and decode it from Shift-JS. but the opposite operation is not supported by the library.
I added the encoding-japanese, in order to convert a string to SHIFT-js and download it.
Here is my code :
const csv = csvParser.unparse({
"fields": ["行形式","取引番号","取引日","支払期限","顧客番号","顧客企業名","顧客電話番号","送付先郵便番号","請求書発行日","郵送","メール送付","取引金額","明細","単価","数量","金額","消費税率","税込対象額_10%","税込対象額_8%","税込対象額_経8%","税込対象額_旧8%","税込対象額_非","税込対象額_対象外"],
"data": [
["取引","transaction-20200218-094750_1","2020/02/18","2020/03/31","DP79","Sample1Corp","03-0000-0000","123-4567","2020/02/19","0","1","110","","","","","","110","","","",""]
]
});
const a = document.createElement("a");
const sjisArray = Encoding.convert(csv, 'SJIS', 'UTF8');
console.log(sjisArray)
a.href = window.URL.createObjectURL(new Blob(['\ufeff'+sjisArray], {type: "text/csv;charset=shift-js"}));
a.download = "取引サンプル.csv";
a.click();
It throw no error, but my csv file when I open it in notepad, it is still in UTF8 with BOM.
I wish to have it in shift-js.
How can I achieve that ?
Your Encoding library is currently returning a DOMString, because you passed such a DOMString as input.
This means that your Blob constructor will convert this DOMString to UTF-8 and that's what you'll have in your file: an UTF-8 version of the UTF-16 representation of the Shift-JIS encoded text.
Least to say, that's not what you want.
Quick looking at that library's docs, it seems that the best would be to pass an ArrayBuffer version of your text to encode, so that it returns to you an Array of the bytes values (like an Uint8Array, except they use a normal Array for whatever reasons...).
Then from that Array of bytes, you'll be able to generate a new ArrayBuffer that you will be able to pass to your Blob without it converting it back to UTF-8.
const csv = Papa.unparse({
"fields": ["行形式","取引番号","取引日","支払期限","顧客番号","顧客企業名","顧客電話番号","送付先郵便番号","請求書発行日","郵送","メール送付","取引金額","明細","単価","数量","金額","消費税率","税込対象額_10%","税込対象額_8%","税込対象額_経8%","税込対象額_旧8%","税込対象額_非","税込対象額_対象外"],
"data": [
["取引","transaction-20200218-094750_1","2020/02/18","2020/03/31","DP79","Sample1Corp","03-0000-0000","123-4567","2020/02/19","0","1","110","","","","","","110","","","",""]
]
});
// First convert our DOMString to an ArrayBuffer
const utf8Array = new TextEncoder().encode( csv );
// pass it to Encoding so we get back an Array of bytes
const sjisArray = Encoding.convert(utf8Array, 'SJIS', 'UTF8');
// now we can make our Blob without auto encoding
const blob = new Blob( [ new Uint8Array( sjisArray ) ] );
const a = document.createElement('a');
a.download = 'Shift-JIS.csv';
a.href = URL.createObjectURL( blob );
a.textContent = 'download';
document.body.append( a );
// just to check we encoded it correctly
readAsText( blob, 'Shift-JIS' )
.then( txt => console.log( 'read back as Shift-JIS:', txt ) );
readAsText( blob, 'utf-8' )
.then( txt => console.log( 'read back as UTF-8:', txt ) );
function readAsText( blob, encoding ) {
return new Promise( (res, rej) => {
const reader = new FileReader();
reader.onerror = rej;
reader.onload = (evt) => res( reader.result );
reader.readAsText( blob, encoding );
} );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.1.0/papaparse.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/encoding-japanese/1.0.30/encoding.min.js"></script>
I have to export table by csv file.
csv file data is from server by Blob type.
Blob {size: 2067, type: "text/csv"}
async exportDocumentsByCsv() {
this.commonStore.setLoading(true)
try {
const result = await DocumentSearchActions.exportDocumentsByCsv({
searchOption: this.documentSearchStore.searchOption
})
// first
// const blob = new Blob([result.body], { type: 'text/csv;charset=utf-8;' })
// second
// const blob = new Blob([`\ufeff${result.body}`], { type: 'text/csv;charset=utf-8;' })
const blob = result.body
console.log('result.body', result.body)
const fileName = `document - search - result.csv`
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
// for IE
window.navigator.msSaveOrOpenBlob(blob, fileName)
} else {
FileSaver.saveAs(blob, fileName)
}
this.commonStore.setLoading(false)
} catch (err) {
alert(err.errorMessage)
this.commonStore.setLoading(false)
}
}
I have to set utf-8 or else because of my language.
I tried to fix this issue, but I don't know how to fix it.
I searched fix this issue by using \ufeff but When I try to use this like
second way, It doesn't work for me.
| [object | Blob] |
Blob doesn't take care of the encoding for you, all it sees is binary data. The only conversion it does is if you pass in an UTF-16 DOMString in the constructor's BlobsList
The best in your situation is to set up everything in your application from server to front as UTF-8 and to ensure that everything is sent using UTF-8. This way, you will be able to directly save the server's response, and it will be in UTF-8.
Now, if you want to convert a text file from a known encoding to UTF-8, you can use a TextDecoder, which can decode a ArrayBuffer view of the binary data from a given encoding to DOMString, which can then be used to generate an UTF-8 Blob:
/* const data = await fetch(url)
.then(resp=>resp.arrayBuffer())
.then(buf => new Uint8Array(buf));
*/
const data = new Uint8Array([147, 111, 152, 94 ]);
// the original data, with Shift_JIS encoding
const shift_JISBlob = new Blob([data]);
saveAs(shift_JISBlob, "shift_JIS.txt");
// now reencode as UTF-8
const encoding = 'shift_JIS';
const domString = new TextDecoder(encoding).decode(data);
console.log(domString); // here it's in UTF-16
// UTF-16 DOMStrings are converted to UTF-8 in Blob constructor
const utf8Blob = new Blob([domString]);
saveAs(utf8Blob, 'utf8.txt');
function saveAs(blob, name) {
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = name;
a.textContent = 'download ' + name;
document.body.append(a);
}
a{display: block;}
This is byte array response I am getting from google api contact-photo:
console.log('byteArray: ', res1.body);
����JFIF��``"����? !1AQaq2B���"#RT����br��3����������0 !1A2Qaq�"��BRS�����
?���Kѐ�V��,���fu0�AկQ�w���y�
x��i�|��F?���;҆�X����������(+:s��iud���c�Gf�e7�jI�;N�d�%�f����+�Uh4q;Ĭ!9ȨD��[��5�ކ�;h��gCt�͌��و1J��q�a��S��^�V��R�����U��K6�<��"�U��~"u�|Q
ڵ��G���;}�ђ��<���sX���>j���hk���~+�^����3�q4��P؝�oZ������4��P{O-j�]�d�c��pG��<7��Q������zd{n��|�`�mɊ��SN�D����}�Hv��0PY�<\�#�T�k!0�R(�Um�n��e�>�a욶˽�8P����{�)���"�
�4��}����6�`���T��!wY�� ��4�y�����+�A]U�M�ֻ⼪�d�N��EcQ`a�u�R��
�
Z"�e/���;-�vL�<c���IH"W2Ga���Ӄ⬨�cݻ#q��c�Y䣃F�G�$�0:�z�" 1��
�S�R�WCh��a���#%#��$�i�y�
u��[�6Ή����(c�Sw˻�G��X3����R��n'�m+>����'
�/;�%�k�4��Z�/l^�z�/l^�z��Z�}k^��!������O����������Dzx�"��>��û#>�#\~{�L-D�k��T�L�����({�TAr9����g}��y�{Լ�.�у�8���^��6��"9+��k��K�V�6�����p�¦�Y�~%b�F�lX����_���v����_�O����A�+�G��e]Q*���z��G|�Y{��f��Y�CI�qu*p�v�T�Z�%*R�Kx��c��Is�D�Y�-���O$��!�`��4M���VX�#v�g��U�̦��2E�W��s�7=}z#��Ԯ� c���t^��n|R2H�� |�����w�k�9��ٵ�o1�U��nC�r#���7���wZ��-�!n����v�p���P�h_dR�����O5�ޟ�
�*"̙����7-rr�{��<��3��#O�S;:/~�"f~Ϋ;IǸ,�V�[K�\���c���d4`6��ѣ��Õ]<ϚN��<��r/Fug<֧���ӢуZ�>z�Cܟ{'c��ˏO��jB��o �����c5�:�6:H�Ώ�c�S<�}{���U_c+�T��D����JY�����=v�&5� �ג3䒮i�Wq�#�$J �ǖ+��4"�FZ��ʗ���ݹ�E�]tV��
!� ��H�Op��)�&���P۷��'�;S�������#�!��/X��GO��iC�8>ȅ:���`$���H��m
I am trying to convert to base64 in nodejs:
base64Image = new Buffer.from(res1.body).toString('base64');
console.log("data:image/png;base64," + base64Image;)
which produces the following base64:
'data:image/png;base64,77+977+977+977+9ABBKRklGAAEBAAABAAEAAO+/ve+/vQDvv70ABQMEDw8NDQ0NEA8ODxANDhAPDw0NDw0QEA8NDg0NDg0NDw8NEA0NDw4NDQ0NFQ0PEhETExMNDRYYFhIYEBITEgEFBQUHBgcPCQkPHBUSFR0VHx0XGB4WHRcXFRUXFR0XGB0dFxUVFRUXFRUXFRUVFRUVFRUXFRUeFRUVFRUVFRUe77+977+9ABEIAGAAYAMBIgACEQEDEQHvv73vv70AHAAAAQQDAQAAAAAAAAAAAAAAAQUGBwgAAgME77+977+9AD8QAAEDAQMIBQkGBwEAAAAAAAEAAgMRBAchBQYSMUFRYXEyQu+/ve+/ve+/vRYiI1JU77+977+977+977+9ExRicu+/ve+/vTPvv73vv73vv73vv73vv73vv70X77+977+9ABwBAAICAwEBAAAAAAAAAAAAAAUGBAcBAggDAO+/ve+/vQAwEQABBAECAwYDCQAAAAAAAAABAAIDBBEFIRIxQQYyUWFx77+9Iu+/ve+/vRQVFkJSU++/ve+/ve+/ve+/ve+/vQAMAwEAAhEDEQA/AO+/ve+/ve+/vUvRkO+/vVbvv73vv70s77+977+977+9ZnUcMO+/vUHVr1Hvv71377+977+977+9ee+/vQt477+977+9ae+/vXzvv73vv70RRj/vv73vv73vv7070obvv71Y77+977+977+977+977+977+977+977+977+977+9KCs6c++/ve+/vWl1ZO+/ve+/ve+/vWMO77+9R2bvv71lNxzvv71qSe+/vTtO77+9ZO+/vSUE77+9Zu+/ve+/vR8A77+977+9K++/vVVoNBxxO8SsIQIWOcioRO+/ve+/vQNb77+9AO+/vTXvv73ehu+/vTto77+977+9ZxxDdO+/vc2M77+977+92YgxSu+/vRHvv71x77+9Ye+/ve+/vVPvv73vv71e77+9Vu+/vQjvv73vv71S77+9f++/ve+/ve+/vQ/vv71V77+977+9Szbvv70877+977+9Iu+/vVXvv73vv70YBn4ide+/vXxRCu+/ve+/vWPvv71G77+9SW9a0KlY77+977+977+9NO+/ve+/ve+/ve+/vVzvv73vv71dS3Dvv70zSyfvv70oI++/vUfvv70c1oBe77+9ZO+/ve+/ve+/vWbvv71GVT0jQ1xAOe+/vVHvv73vv71n77+93aDvv704z6bvv73vv73vv73vv71tf++/ve+/ve+/vWZxJO+/vWpNcTvvv73vv73vv71MV++/ve+/ve+/ve+/vSvvv70NHNq177+977+9R++/ve+/ve+/vTt977+90ZLXihHvv73vv70SPO+/ve+/vRfvv71zWO+/ve+/ve+/vT5q77+977+977+9aGvvv70Y77+977+9fivvv71e77+977+977+977+9M++/vXE077+977+9UB3Yne+/vW9a77+977+9G++/ve+/ve+/ve+/vTTvv73vv71QDntPLWrvv71d77+9ZO+/vWPvv70AA++/vXAGR++/ve+/vTw3Ae+/vRDvv71R77+9He+/ve+/ve+/ve+/ve+/vXpke27vv73vv71877+9YO+/vW3Jigfvv73vv71TTu+/vUTvv73vv73vv73vv71977+9SHYb77+977+9MFBZ77+9PFzvv70j77+9VO+/vWsRITDvv71SKO+/vQBVbe+/vW7vv73vv71l77+9Pu+/vWHsmrbLve+/vThQ77+977+9H++/ve+/vXvvv70p77+977+977+9Iu+/vQvvv73vv73vv707I34sPCvvv73vv71pQe+/ve+/ve+/ve+/vSHvv71u1a1dZu+/vVdl77+9H++/vXHvv73vv70N77+9NO+/vQ7vv71977+977+977+977+9Nu+/vWDvv73vv73vv71U77+977+9IXdZ77+9He+/vSDvv70D77+9NO+/vXkY77+977+977+977+9Au+/vSvvv71BXVXvv71N77+91rsG4ryq77+9ZATvv71O77+977+9RWNRYGHvv71177+9Uu+/vQvvv70LWiLvv71lLwDvv70a77+977+9Oy3vv712TO+/vTxj77+977+9HO+/vUlIIlcyR2Hvv73vv73vv73Tg+KsqO+/vWPduyNx77+977+9Y++/vVnko4NG77+9R++/vSTvv70wOu+/vXrvv70iCQ8x77+977+9DO+/vVPvv71S77+9V0No77+977+9Ye+/ve+/ve+/vUAlI++/ve+/vSTvv71p77+9ee+/vQt177+977+9W++/vTbOie+/ve+/ve+/ve+/vShj77+9BlN3y7sf77+9R++/ve+/vVgz77+977+977+9Ee+/vQBS77+977+9bifvv71tKz7vv73vv73vv73vv70nDO+/vQ4vO++/vSXvv71r77+9NO+/ve+/vVrvv70vbF7vv70feu+/vS9sXu+/vR9677+977+9Wu+/vX1rXu+/ve+/vSHvv73vv73vv73vv73vv73vv71P77+9Fe+/ve+/ve+/ve+/ve+/vRHvv73vv73vv73vv73Hsnjvv70i77+977+9Pu+/ve+/vcO7IxAZDz7vv70jXH5777+9TC1E77+9a++/ve+/vR5U77+9TO+/ve+/vU8977+9Se+/ve+/vVxRHXkk77+9Me+/vSc877+977+9Pe+/ve+/ve+/ve+/ve+/vQB1Uu+/vWLvv70N77+977+977+9KHsS77+9VEFyOe+/ve+/ve+/ve+/vWd9G9eO77+977+9Dgd577+9e9S877+9Lu+/vdGD77+9OO+/ve+/ve+/vQVe77+977+9Nu+/ve+/vSI5GSvvv73vv71r77+977+9S++/vVbvv70277+977+977+977+977+9cO+/vcKm77+9We+/vX4lYu+/vUbvv71sWO+/vRfvv73vv73vv71f77+977+9D++/vXbvv73vv73vv73vv71f77+9T++/ve+/ve+/ve+/vRgaQe+/vSvvv71H77+977+9ZV1RKu+/vRvvv73vv71677+977+9R3zvv71Ze++/vQbvv71m77+977+9We+/vQdDSe+/vXF1KnDvv71277+9VO+/vVrvv70XJREwHO+/vQBKNO+/vWzvv70z77+9yZbvv715Ru+/ve+/ve+/vSLvv70177+9Elzvv70HEkAI3Kfvv73vv73vv70NGSpS77+9S3jvv73vv71j77+977+9SXMG77+9HUTvv70UWe+/vS3vv73vv73vv71PJO+/ve+/vSHvv70FYO+/ve+/vTRN77+9H++/ve+/vVZY77+9QB1277+9Z++/ve+/vVXvv73Mphjvv73vv70XMkXvv71X77+977+9c++/vTc9fXoj77+977+91K7vv70gY++/ve+/ve+/vXRe77+977+9bnxSMkjOi++/ve+/vSB8DwPvv73vv73vv73vv73vv71377+9a++/vTnvv70H77+9A9m177+9bzHvv71V77+977+9bkPvv71yQO+/ve+/vRPvv70eNx3vv73vv73vv713FFrvv73vv70t77+9IRpu77+977+977+977+9du+/vXDvv73vv73vv71Q77+9aF8UZFLvv73vv73vv70O77+9Bu+/vU8SNe+/vd6f77+9DO+/ve+/vTxV77+977+977+977+9De+/vQAqIsyZ77+9GxTvv70F77+977+9Ny1ychLvv71777+9Fe+/vTzvv73vv70VM++/ve+/vSNP77+9ElM7Oi9+77+9GCIAZn7OqztJx7gs77+9VgHvv71bS3YI77+9XO+/ve+/ve+/vdWXY++/ve+/ve+/vWQ0AGA277+977+90aPvv73vv70Zw5VdPM+aTu+/ve+/vTwA77+977+9chgvRnVnPNan77+977+977+906LRg1oP77+9Pnrvv71D3J97JxVjGe+/ve+/vcuPTwTvv73vv71qQu+/ve+/vW8g77+977+977+977+977+9YzXvv70677+9NjpI77+9zo/vv71j77+9Uzzvv719e++/ve+/ve+/vSzvv73vv73vv70abx7vv71fONeq3qt8e1Ftfu+/vWtVIHfvv73vv71aae+/ve+/ve+/vQ8A77+9FzVC77+977+9dsau77+9We+/vTXvv71Ix73vv73vv70AVTYW77+9Xu+/vVZLE2QYKe+/ve+/vUZa77+977+9ypfvv73vv73vv73duRDvv71F77+9XXRW77+977+9DSLvv73vv70gee+/ve+/ve+/vWHvv70UJe+/ve+/ve+/vWjvv73vv73vv73vv73vv709du+/vSYeNRrvv70aIO+/vdeSM+SSrmnvv71Xce+/vSPvv70kSiACIO+/vceWKxfvv70d77+9YAg0IhYNVV9jK++/vVQJRO+/ve+/vRXvv73vv71KWQshTWh277+9Me+/vU4gUe+/ve+/ve+/vRTHmBdI77+977+9Ze+/vREj77+9Ie+/ve+/vQ4dL1jvv73vv71HT++/ve+/vWlD77+9OD7IhToT77+977+977+9YCQb77+977+977+9SO+/ve+/vW0NIe+/vSDvv70b77+9SO+/vU9w77+9Bu+/vSnvv70mUQjvv73vv70A77+9BRdQEdu377+977+9Jxzvv707U++/ve+/ve+/ve+/ve+/ve+/ve+/vQ==',
However, assigning this to <img src="base64 data here"/> doesn't generate image.
Here is the google api example: https://developers.google.com/google-apps/contacts/v3/#retrieving_a_contacts_photo
What am I doing wrong?
JFIF suggests you're actually converting a .jpg file, not a .png.
Make sure the file type (e.g. .png) matches the Mime type (e.g. "image/png").
Also consider specifying charset.
SUGGESTED CHANGE:
base64Image = new Buffer.from(res1.body).toString('base64');
console.log("data:image/jpeg;charset=utf-8;base64," + base64Image;)
<= Assuming it's really a jpeg file
Don't forget to make the corresponding change in your HTML, too...
when you try to do only get a request without specifying the encoding type for an image which is coming from the third party, then the response of the body will be the raw data which you are getting in bytearray variable , so you have add header encoding: "binary" so the response will come in binary format and then you use Buffer and BUffer.from to convert that binary data to base64 and use it in your <img src"data:image/png;base64,yourbase64data"
function getImage(imageUrl) {
var options = {
url: `${imageUrl}`,
encoding: "binary"
};
request.get(options, function (err, resp, body) {
if (err) {
reject(err);
} else {
var prefix = "data:" + resp.headers["content-type"] + ";base64,";
var img = new Buffer(body.toString(), "binary").toString("base64");// var img = new Buffer.from(body.toString(), "binary").toString("base64");
dataUri = prefix + img;
console.log(dataUri);
}
})
}
when use promise
function getImage(imageUrl) {
var options = {
url: `${imageUrl}`,
encoding: "binary"
};
return new Promise(function (resolve, reject) {
request.get(options, function (err, resp, body) {
if (err) {
reject(err);
} else {
var prefix = "data:" + resp.headers["content-type"] + ";base64,";
var img = new Buffer(body.toString(), "binary").toString("base64");// var img = new Buffer.from(body.toString(), "binary").toString("base64");
dataUri = prefix + img;
console.log(dataUri);
resolve(dataUri);
}
})
})}
there is one node module also for this form where i got the solution https://www.npmjs.com/package/imageurl-base64
if you want to read the image form your local disk the fs module help you
var prefix = "data:" + "content-type" + ";base64,";
img: fs.readFileSync(`pathtothelocalimage`, 'base64')
//img: fs.readFile(`pathtothelocalimage`, 'base64')
dataUri = prefix + img;
Is there a script (javascript / client side). That create data URIs on the fly. Now i create data URIs with a online base64 creator. And then put that output in the css file. But when i changing the images. Its a lot of work to do it. Is there a script, that can do it for me.?
The modern browsers now have good support for base64 encoding and decoding. There are two functions respectively for decoding and encoding base64 strings:
atob() decodes a string of base-64 data
btoa() creates a base-64 encoded ASCII string from a "string" of binary data
This let's you create data uri's easily i.e
var longText = "Lorem ipsum....";
var dataUri = "data:text/plain;base64," + btoa(longText);
//a sample api expecting an uri
d3.csv(dataUri, function(parsed){
});
As a complete solution to your scenario, you can use fetch to get a blob representation of your image, and then use FileReader to convert the blob in its base64 representation
// get an image blob from url using fetch
let getImageBlob = function(url){
return new Promise( async resolve=>{
let resposne = await fetch( url );
let blob = resposne.blob();
resolve( blob );
});
};
// convert a blob to base64
let blobToBase64 = function(blob) {
return new Promise( resolve=>{
let reader = new FileReader();
reader.onload = function() {
let dataUrl = reader.result;
resolve(dataUrl);
};
reader.readAsDataURL(blob);
});
}
// combine the previous two functions to return a base64 encode image from url
let getBase64Image = async function( url ){
let blob = await getImageBlob( url );
let base64 = await blobToBase64( blob );
return base64;
}
// test time!
getBase64Image( 'http://placekitten.com/g/200/300' ).then( base64Image=> console.log( base64Image) );
One way is to make a Blob of an object, and then use URL.createObjectURL()
let a = URL.createObjectURL(new Blob([JSON.stringify({whatever: "String..."}, null, 2)]))
console.log(a)