I am building an application where my client required to upload some images and download them back when required I am using Mysql Database for rest application so I have decided to save all images as Blob file in my database in this I need to accomplish below task
1.upload image file from client side to node js express server using XMLHttpRequest
2.save image as blob file from node js express backend to Mysql Databse
3.retrive Image back when required from Mysql Databse using node js express backend and send image file to client
4.display/Download Image received from backend
from this above 4 tasks I was able to complete 3 but at unable to complete last one details of code is as per below
please advice how to convert blob file back to Image and display or download same at client side
What I have tried:
1.upload image file from client side to node js express server using XMLHttpRequest
var file=document.getElementById("uploadedfile").files[0];
let formData=new FormData();
formData.append("file",file);
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){}
xhttp.open("POST","/formula144",true);
xhttp.send(formData);
2.save image as blob file from node js express backend to Mysql Databse
if(!req.files){
console.log("No Files Found");
}else{
let imagedata=req.files.file;
console.log(imagedata);
let sql="UPDATE form92 SET form92.rc_photo=? WHERE form92.trucknoform11='RJ-52GA-1362'";
let query=conn.query(sql,[imagedata.data],(err,results)=>{
if(err){
console.log(err);
}
});
}
3.retrive Image back when required from Mysql Databse using node js express backend and send image file to client
sql3="SELECT form92.rc_photo FROM form92 WHERE form92.trucknoform11='"+req.query.truck_no+"'";
let query3=conn.query(sql3,(err,results3)=>{
if(err){
console.log(err);
}else{
res.send(results3[0].rc_photo);
}
});
4.display/Download Image received from backend
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){
if(this.readyState==4&&this.status==200){
var myblobObj=this.response;
var encodedUri=encodeURI(myblobObj);
var link=document.createElement('a');
link.setAttribute("href",encodedUri);
link.setAttribute("download","file.jpg");
document.body.appendChild(link);
link.click();
}
}
xhttp.open("GET","/formula143a?"+fdata,true);
xhttp.setRequestHeader('Content-Type','application/X-www-form-urlencoded');
xhttp.send();