Using Node Js Multer I am uploading an image to the database as a blob. This happens from javascript ajax xmlhttp request to express js endpoint.
index.html uploading image request
input.addEventListener('change', function () {
uploadIMagetoDatabase(input.files[0]);
getIMagefromDatabase(imgtag);
});
uploadIMagetoDatabase(image){
var data, xhr;
data = new FormData();
data.append('imageProfile',image);
xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000/upload', true);
xhr.onreadystatechange = function (response) {
// document.getElementById("result").innerHTML = xhr.responseText
};
xhr.send(data);
}
express js image database upload
router.post('/upload', upload.single('imageProfile'),function(req,res){
const imageProfile = req.file;
var image=imageProfile;
var sql='Insert into Uploads (id,image) VALUES("2",cast("'+image+'" AS BINARY));';
connection.query(sql, function (err, data) {
if (err) {
// some error occured
console.log("database error-----------"+err);
} else {
// successfully inserted into db
console.log("database insert sucessfull-----------");
}
});
});
so according to my knowledge image gets uploaded as blob to mysql database successfully.
now the problem is fetching and viewing the image from database.
express js fetch image from database
router.get('/getimage',function(req,res){
var sql = 'SELECT image FROM Uploads';
connection.query(sql, function (err, data) {
if (err) {
// some error occured
console.log("database error-----------"+err);
} else {
// successfully inserted into db
console.log("database select sucessfull-----------"+data.length);
res.json({'image':data[0].image});
}
});
});
index.html show database from express js endpoint as a object url
getIMagefromDatabase(imgtag){
$.get("http://localhost:3000/getimage",function(data,status){
console.log("data---"+JSON.stringify(data));
let url = URL.createObjectURL( new Blob([data["image"]], { type: 'image/jpeg'
}))
imgtag.src=url;
});
}
json response of image blob
{"image":{"type":"Buffer","data":
[91,111,98,106,101,99,116,32,79,98,106,101,99,116,93]}}
node js multer req.file
{
fieldname: 'imageProfile',
originalname: 'picture_orig.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'uploads/',
filename: '7b62ab418013514bab9ba43327fa171c',
path: 'uploads/7b62ab418013514bab9ba43327fa171c',
size: 34117
}
This image is not getting displayed as a ObjectURL in index.html. Anything wrong that is done here?
new Blob([data["image"]]->new Blob([new Uint8Array(data["image"]["data"])]