1

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?

15
  • try: new Blob([data["image"]] -> new Blob([new Uint8Array(data["image"]["data"])] Commented Jun 26 at 11:26
  • The data you are uploading isn't what you think it is. But we can't help you until you show us the code that creates the first image variable contents. i.e in the line data.append('imageProfile',image); Commented Jun 26 at 13:17
  • Ray Wallace I have updated my code.image variable is created from the input file change listener files[0]. Commented Jun 27 at 3:16
  • traynor i tried it but it does not work. Commented Jun 27 at 3:17
  • 1
    Traynor it works I read the image file from path and inserted as blob to DB. then using object url I read the image successfully. Commented Jun 27 at 15:41

1 Answer 1

0

Should read the image from node js file path and insert the bytes as a blob to database. Then it works.


router.post('/upload', upload.single('imageProfile'),function(req,res){

  const image = req.file;

  fs.readFile('./path/'+image.filename, function(err, data) {
    if (err) throw err 

    var sql = 'Insert into Uploads (id,image) VALUES ?';
    var values=[["1",data]]; 

    connection.query(sql,[values], function (err, data) {
        if (err) {
        
            console.log("database error-----------"+err);
        } else {
            
            console.log("database insert sucessfull-----------");
            
        }
    });


  })


});

Then from this blob creating the object url is possible without a problem.The blob should be fetched from the database and should be sent to the front as a json object.Then it can be displayed as shown below.

 $.get("http://localhost:3000/getimage",function(data,status){

 const buffer = new Uint8Array(data["image"]["data"]).buffer;
 let url = URL.createObjectURL( new Blob([buffer], { type: 'image/jpeg' }));
 imgtag.src=url;

 });

convert-byte-array-to-blob-object-on-client-side-in-node-js

nodejs-how-to-read-and-output-jpg-image

Sign up to request clarification or add additional context in comments.

2 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
answer was improved and supporting links were added.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.