Reputation: 41
Is there something wrong with my code? I am asking because I failed to display the image in my browser. I have tried to decode the base64 image into png but I'm still not able to display the image. My URL format as below: data:image/jpeg;base64,iVBORw0kGgoAAAANSUhgAAAeAA...
My php code
//Connect to database
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("studioassessor_01") or die (mysql_error());
$sql = "SELECT * FROM frame";
$result = mysql_query($sql);
if($result == FALSE){
die(mysql_error());
}
while($row = mysql_fetch_array($result)){
header("Content-type: image/png");
echo '<img src="data:image/png;base64,' . base64_decode($row['url']) . '" />';
}
After I have test for many rounds, I found that there is something wrong to my request header part in ajax scripting. The request header had changed my base 64 string value to another value.
function saveIt(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert("Save successfully!");
}
}
var value1 = document.getElementById("url").value ;
var value2 = document.getElementById("time").value;
var value3 = document.getElementById("note").value;
xmlhttp.open("POST", "insertFrame.php", true);
xmlhttp.setRequestHeader("Content-type:image/png","application/x-www-form-urlencoded");
xmlhttp.send("url="+ value1 + "&time=" + value2 + "¬e=" + value3);
}
So, may I ask again what should i do for the xmlhttp.setRequestHeaderPart?
Upvotes: 1
Views: 8246
Reputation: 360602
Yes, you're decoding the base64 data into raw binary, but telling the browser that it's still base64. That's not going to work.
echo '<img src="data:image/png;base64,' . $row['url'] . '" />';
should be all you need. no decode call at all. Note that you couldn't really dump the raw binary into a data uri, even if you wanted to - it will randomly (and naturally) contain "
and other html meta-characters, introducing html injection problems. you'd have to htmlspecialchars()
the binary string, and then figure out if there's an encoding type raw-binary-with-html-characters-escaped
Upvotes: 1