Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
12
rated 0 times [  16] [ 4]  / answers: 1 / hits: 32320  / 14 Years ago, sat, march 19, 2011, 12:00:00

This should be simple enough, but after wrestling with it for hours, I still can't get it to work. So far, all my attempts have resulted in the image becoming 'corrupted or truncated', according to firefox.



Retrieve the image from the server with a jquery-ajax call:



 $.ajax({
async: false,
url: db[key][DocumentLink],
success: function (result2) {



Base64 encode the image, and store it in localStore:

In this example I'm using the jquery base64-encoding plugin, but I've tried several.



                        var dbKey = Doc  + db[key][ID] +   + db[key][Title];
console.log(storing: + db[key][DocumentLink] + in + dbKey + n);
localStorage.removeItem(dbKey);
var base64Image = $.base64Encode(result2);
console.log(base64Image.length);
localStorage.setItem(dbKey, base64Image);
console.log(is stored: + db[key][DocumentLink] + in + dbKey + n);
}
})



Display the image with a data url:



function openImageFromDB(dbKey) {
console.log(Trying to display image with key + dbKey);
var base64Img = localStorage.getItem(dbKey);
document.getElementById(documentHolder).src='data:image/jpeg;base64,' + base64Img;
}



The corresponding img:



 <img id=documentHolder alt=Image view placeholder src= />



However, on every try, firefox displays:



Image corrupt or truncated: data:image/jpeg;base64,77+977+977+977+9a<... much longer string>



The Url: points to a valid jpeg image, and the base64Image.length and the error message show that the var / localStorage actually contain what seems to be base64 encoded data.



Any ideas?


More From » ajax

 Answers
0




Javascript (AJAX call)



function LoadImg(filename) {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject(Microsoft.XMLHTTP);
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(documentHolder).src = data:image/png;base64, + xmlhttp.responseText;
}
};
xmlhttp.open(GET, 'load.php?LoadImg='+filename );
xmlhttp.send(null);
}


PHP ( load.php )



<?php
if (isset($_GET['LoadImg'])) {
header(Content-Type: image/png);
$file = file_get_contents($_GET['LoadImg']);
echo base64_encode($file);
}
?>





Read this may help you:







PS: maybe your Base64 is wrong?


[#93185] Friday, March 18, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
luizc

Total Points: 623
Total Questions: 87
Total Answers: 103

Location: Zimbabwe
Member since Sat, Feb 27, 2021
3 Years ago
;