Vuejs load image from nodejs res.sendFile










0















In my vue's created, I use axios to connect to my server to retrieve an image as below:



created() 
this.schoolID = localStorage.getItem('schoolID')
console.log(this.schoolID)
axios.get(process.env.MY_URL + '/public/logo',
params:
schoolID: this.schoolID

)
.then(response =>
this.logo = response.data
console.log(this.logo)
)
.catch(e =>
console.log(e.response)
this.errors.push(e)
)
,


and my nodejs will receive the request and send the response like below



router.get('/logo', function(req, res)
School.findOne( _id: mongoose.mongo.ObjectId(req.query.schoolID) ).exec().then(function (data)
if (!data)
console.log("error... no logo found for the given id: " + req.query.schoolID)
return res.status(200).send(success: false, msg: 'No logo found.');
else
res.sendFile(__dirname + '/uploads/' + data.logo);

);
);


my image should be loaded into my code



<img :src="this.logo">


I'm positive I got (at least the nodejs) the image file correctly because if I just append some string at the end of data.logo, I will get 404 not found error in my Vue and ENOENT: no such file or directory, stat 'D:webmusleh-apiuploads1542208727664_logo_sdam.png' error in my nodejs



However, no image is being loaded,and my console.log(this.logo) will display funny symbols which I assume is the image file if we try to open it using any text editor.



What did I miss?










share|improve this question


























    0















    In my vue's created, I use axios to connect to my server to retrieve an image as below:



    created() 
    this.schoolID = localStorage.getItem('schoolID')
    console.log(this.schoolID)
    axios.get(process.env.MY_URL + '/public/logo',
    params:
    schoolID: this.schoolID

    )
    .then(response =>
    this.logo = response.data
    console.log(this.logo)
    )
    .catch(e =>
    console.log(e.response)
    this.errors.push(e)
    )
    ,


    and my nodejs will receive the request and send the response like below



    router.get('/logo', function(req, res)
    School.findOne( _id: mongoose.mongo.ObjectId(req.query.schoolID) ).exec().then(function (data)
    if (!data)
    console.log("error... no logo found for the given id: " + req.query.schoolID)
    return res.status(200).send(success: false, msg: 'No logo found.');
    else
    res.sendFile(__dirname + '/uploads/' + data.logo);

    );
    );


    my image should be loaded into my code



    <img :src="this.logo">


    I'm positive I got (at least the nodejs) the image file correctly because if I just append some string at the end of data.logo, I will get 404 not found error in my Vue and ENOENT: no such file or directory, stat 'D:webmusleh-apiuploads1542208727664_logo_sdam.png' error in my nodejs



    However, no image is being loaded,and my console.log(this.logo) will display funny symbols which I assume is the image file if we try to open it using any text editor.



    What did I miss?










    share|improve this question
























      0












      0








      0








      In my vue's created, I use axios to connect to my server to retrieve an image as below:



      created() 
      this.schoolID = localStorage.getItem('schoolID')
      console.log(this.schoolID)
      axios.get(process.env.MY_URL + '/public/logo',
      params:
      schoolID: this.schoolID

      )
      .then(response =>
      this.logo = response.data
      console.log(this.logo)
      )
      .catch(e =>
      console.log(e.response)
      this.errors.push(e)
      )
      ,


      and my nodejs will receive the request and send the response like below



      router.get('/logo', function(req, res)
      School.findOne( _id: mongoose.mongo.ObjectId(req.query.schoolID) ).exec().then(function (data)
      if (!data)
      console.log("error... no logo found for the given id: " + req.query.schoolID)
      return res.status(200).send(success: false, msg: 'No logo found.');
      else
      res.sendFile(__dirname + '/uploads/' + data.logo);

      );
      );


      my image should be loaded into my code



      <img :src="this.logo">


      I'm positive I got (at least the nodejs) the image file correctly because if I just append some string at the end of data.logo, I will get 404 not found error in my Vue and ENOENT: no such file or directory, stat 'D:webmusleh-apiuploads1542208727664_logo_sdam.png' error in my nodejs



      However, no image is being loaded,and my console.log(this.logo) will display funny symbols which I assume is the image file if we try to open it using any text editor.



      What did I miss?










      share|improve this question














      In my vue's created, I use axios to connect to my server to retrieve an image as below:



      created() 
      this.schoolID = localStorage.getItem('schoolID')
      console.log(this.schoolID)
      axios.get(process.env.MY_URL + '/public/logo',
      params:
      schoolID: this.schoolID

      )
      .then(response =>
      this.logo = response.data
      console.log(this.logo)
      )
      .catch(e =>
      console.log(e.response)
      this.errors.push(e)
      )
      ,


      and my nodejs will receive the request and send the response like below



      router.get('/logo', function(req, res)
      School.findOne( _id: mongoose.mongo.ObjectId(req.query.schoolID) ).exec().then(function (data)
      if (!data)
      console.log("error... no logo found for the given id: " + req.query.schoolID)
      return res.status(200).send(success: false, msg: 'No logo found.');
      else
      res.sendFile(__dirname + '/uploads/' + data.logo);

      );
      );


      my image should be loaded into my code



      <img :src="this.logo">


      I'm positive I got (at least the nodejs) the image file correctly because if I just append some string at the end of data.logo, I will get 404 not found error in my Vue and ENOENT: no such file or directory, stat 'D:webmusleh-apiuploads1542208727664_logo_sdam.png' error in my nodejs



      However, no image is being loaded,and my console.log(this.logo) will display funny symbols which I assume is the image file if we try to open it using any text editor.



      What did I miss?







      node.js vue.js






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 14 '18 at 17:04









      iminimin

      1,62673565




      1,62673565






















          2 Answers
          2






          active

          oldest

          votes


















          0














          I believe what you need to do is this in your HTML code, assuming that your image is base64 encoded:



          <img alt="Awesome logo" :src="'data:image/png;base64,'+this.logo" />


          Here is the source



          Addition, as above seems not to work:



          After some research I think we are not completely on the wrong path here, but give this a try:



          On the NodeJS side try this:



           }else
          var img = fs.readFile('__dirname + '/uploads/' + data.logo', function (err, data)
          var contentType = 'image/png';
          var base64 = Buffer.from(data).toString('base64');
          base64='data:image/png;base64,'+base64;
          res.send(base64);
          );
          );
          });


          then in VueJS as before:



          <img alt="Awesome logo" :src="this.logo" />


          OR THE EASY WAY:



          On the NodeJS side try this:



           }else
          // prefix your domain if your API serves to other domains
          res.send('/uploads/' + data.logo');
          );
          });
          });


          Also here Vuejs code remains as you did it.






          share|improve this answer

























          • Unfortunately, the image is still not being loaded. If I try to open the (not being displayed) image in new tab, it will just show this o the url bar data:image/png;base64,%EF%BF%BDPNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%EF%BF%BD%00%00%00%EF%BF%BD%08%02%00

            – imin
            Nov 15 '18 at 7:36











          • I updated my answer, see above....

            – Edwin Krause
            Nov 15 '18 at 10:30


















          0














          Assuming that you want to pass the school ID to request the image, you don't need axios to make the request, you can use directly the <img src> tag with a dynamic parameter to request the data. You also need to change you express configuration to return the image with Content-Type:'image/png' or whatever is the mime type of your data.



          Then on vue template you will need to pass the school id to the dynamic route, the data request and handling will be done by the img element



          <img :src="`/logo/$schoolID">


          .



          router.get('/logo/:schoolID', function(req, res)
          School.findOne( _id: mongoose.mongo.ObjectId(req.params.schoolID) ).exec().then(function (data)
          if (!data)
          console.log("error... no logo found for the given id: " + req.params.schoolID)
          return res.status(200)
          .send(success: false, msg: 'No logo found.');
          else
          res.type('png')
          .sendFile(__dirname + '/uploads/' + data.logo);

          );
          );





          share|improve this answer

























          • Apparently I can't just add setHeader with sendFile, so I do this res.append('Content-Type', 'image/png') res.status(200).sendFile(__dirname + '/uploads/' + data.logo); but still, the image is not being displayed

            – imin
            Nov 15 '18 at 7:31











          • sorry I'm missed something you have to set the type for sendFile, I've edit the response. Also check expressjs.com/en/api.html#res.sendFile

            – cal_br_mar
            Nov 15 '18 at 20:15










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53305365%2fvuejs-load-image-from-nodejs-res-sendfile%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          I believe what you need to do is this in your HTML code, assuming that your image is base64 encoded:



          <img alt="Awesome logo" :src="'data:image/png;base64,'+this.logo" />


          Here is the source



          Addition, as above seems not to work:



          After some research I think we are not completely on the wrong path here, but give this a try:



          On the NodeJS side try this:



           }else
          var img = fs.readFile('__dirname + '/uploads/' + data.logo', function (err, data)
          var contentType = 'image/png';
          var base64 = Buffer.from(data).toString('base64');
          base64='data:image/png;base64,'+base64;
          res.send(base64);
          );
          );
          });


          then in VueJS as before:



          <img alt="Awesome logo" :src="this.logo" />


          OR THE EASY WAY:



          On the NodeJS side try this:



           }else
          // prefix your domain if your API serves to other domains
          res.send('/uploads/' + data.logo');
          );
          });
          });


          Also here Vuejs code remains as you did it.






          share|improve this answer

























          • Unfortunately, the image is still not being loaded. If I try to open the (not being displayed) image in new tab, it will just show this o the url bar data:image/png;base64,%EF%BF%BDPNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%EF%BF%BD%00%00%00%EF%BF%BD%08%02%00

            – imin
            Nov 15 '18 at 7:36











          • I updated my answer, see above....

            – Edwin Krause
            Nov 15 '18 at 10:30















          0














          I believe what you need to do is this in your HTML code, assuming that your image is base64 encoded:



          <img alt="Awesome logo" :src="'data:image/png;base64,'+this.logo" />


          Here is the source



          Addition, as above seems not to work:



          After some research I think we are not completely on the wrong path here, but give this a try:



          On the NodeJS side try this:



           }else
          var img = fs.readFile('__dirname + '/uploads/' + data.logo', function (err, data)
          var contentType = 'image/png';
          var base64 = Buffer.from(data).toString('base64');
          base64='data:image/png;base64,'+base64;
          res.send(base64);
          );
          );
          });


          then in VueJS as before:



          <img alt="Awesome logo" :src="this.logo" />


          OR THE EASY WAY:



          On the NodeJS side try this:



           }else
          // prefix your domain if your API serves to other domains
          res.send('/uploads/' + data.logo');
          );
          });
          });


          Also here Vuejs code remains as you did it.






          share|improve this answer

























          • Unfortunately, the image is still not being loaded. If I try to open the (not being displayed) image in new tab, it will just show this o the url bar data:image/png;base64,%EF%BF%BDPNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%EF%BF%BD%00%00%00%EF%BF%BD%08%02%00

            – imin
            Nov 15 '18 at 7:36











          • I updated my answer, see above....

            – Edwin Krause
            Nov 15 '18 at 10:30













          0












          0








          0







          I believe what you need to do is this in your HTML code, assuming that your image is base64 encoded:



          <img alt="Awesome logo" :src="'data:image/png;base64,'+this.logo" />


          Here is the source



          Addition, as above seems not to work:



          After some research I think we are not completely on the wrong path here, but give this a try:



          On the NodeJS side try this:



           }else
          var img = fs.readFile('__dirname + '/uploads/' + data.logo', function (err, data)
          var contentType = 'image/png';
          var base64 = Buffer.from(data).toString('base64');
          base64='data:image/png;base64,'+base64;
          res.send(base64);
          );
          );
          });


          then in VueJS as before:



          <img alt="Awesome logo" :src="this.logo" />


          OR THE EASY WAY:



          On the NodeJS side try this:



           }else
          // prefix your domain if your API serves to other domains
          res.send('/uploads/' + data.logo');
          );
          });
          });


          Also here Vuejs code remains as you did it.






          share|improve this answer















          I believe what you need to do is this in your HTML code, assuming that your image is base64 encoded:



          <img alt="Awesome logo" :src="'data:image/png;base64,'+this.logo" />


          Here is the source



          Addition, as above seems not to work:



          After some research I think we are not completely on the wrong path here, but give this a try:



          On the NodeJS side try this:



           }else
          var img = fs.readFile('__dirname + '/uploads/' + data.logo', function (err, data)
          var contentType = 'image/png';
          var base64 = Buffer.from(data).toString('base64');
          base64='data:image/png;base64,'+base64;
          res.send(base64);
          );
          );
          });


          then in VueJS as before:



          <img alt="Awesome logo" :src="this.logo" />


          OR THE EASY WAY:



          On the NodeJS side try this:



           }else
          // prefix your domain if your API serves to other domains
          res.send('/uploads/' + data.logo');
          );
          });
          });


          Also here Vuejs code remains as you did it.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 15 '18 at 10:29

























          answered Nov 14 '18 at 18:49









          Edwin KrauseEdwin Krause

          1,09111122




          1,09111122












          • Unfortunately, the image is still not being loaded. If I try to open the (not being displayed) image in new tab, it will just show this o the url bar data:image/png;base64,%EF%BF%BDPNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%EF%BF%BD%00%00%00%EF%BF%BD%08%02%00

            – imin
            Nov 15 '18 at 7:36











          • I updated my answer, see above....

            – Edwin Krause
            Nov 15 '18 at 10:30

















          • Unfortunately, the image is still not being loaded. If I try to open the (not being displayed) image in new tab, it will just show this o the url bar data:image/png;base64,%EF%BF%BDPNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%EF%BF%BD%00%00%00%EF%BF%BD%08%02%00

            – imin
            Nov 15 '18 at 7:36











          • I updated my answer, see above....

            – Edwin Krause
            Nov 15 '18 at 10:30
















          Unfortunately, the image is still not being loaded. If I try to open the (not being displayed) image in new tab, it will just show this o the url bar data:image/png;base64,%EF%BF%BDPNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%EF%BF%BD%00%00%00%EF%BF%BD%08%02%00

          – imin
          Nov 15 '18 at 7:36





          Unfortunately, the image is still not being loaded. If I try to open the (not being displayed) image in new tab, it will just show this o the url bar data:image/png;base64,%EF%BF%BDPNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%EF%BF%BD%00%00%00%EF%BF%BD%08%02%00

          – imin
          Nov 15 '18 at 7:36













          I updated my answer, see above....

          – Edwin Krause
          Nov 15 '18 at 10:30





          I updated my answer, see above....

          – Edwin Krause
          Nov 15 '18 at 10:30













          0














          Assuming that you want to pass the school ID to request the image, you don't need axios to make the request, you can use directly the <img src> tag with a dynamic parameter to request the data. You also need to change you express configuration to return the image with Content-Type:'image/png' or whatever is the mime type of your data.



          Then on vue template you will need to pass the school id to the dynamic route, the data request and handling will be done by the img element



          <img :src="`/logo/$schoolID">


          .



          router.get('/logo/:schoolID', function(req, res)
          School.findOne( _id: mongoose.mongo.ObjectId(req.params.schoolID) ).exec().then(function (data)
          if (!data)
          console.log("error... no logo found for the given id: " + req.params.schoolID)
          return res.status(200)
          .send(success: false, msg: 'No logo found.');
          else
          res.type('png')
          .sendFile(__dirname + '/uploads/' + data.logo);

          );
          );





          share|improve this answer

























          • Apparently I can't just add setHeader with sendFile, so I do this res.append('Content-Type', 'image/png') res.status(200).sendFile(__dirname + '/uploads/' + data.logo); but still, the image is not being displayed

            – imin
            Nov 15 '18 at 7:31











          • sorry I'm missed something you have to set the type for sendFile, I've edit the response. Also check expressjs.com/en/api.html#res.sendFile

            – cal_br_mar
            Nov 15 '18 at 20:15















          0














          Assuming that you want to pass the school ID to request the image, you don't need axios to make the request, you can use directly the <img src> tag with a dynamic parameter to request the data. You also need to change you express configuration to return the image with Content-Type:'image/png' or whatever is the mime type of your data.



          Then on vue template you will need to pass the school id to the dynamic route, the data request and handling will be done by the img element



          <img :src="`/logo/$schoolID">


          .



          router.get('/logo/:schoolID', function(req, res)
          School.findOne( _id: mongoose.mongo.ObjectId(req.params.schoolID) ).exec().then(function (data)
          if (!data)
          console.log("error... no logo found for the given id: " + req.params.schoolID)
          return res.status(200)
          .send(success: false, msg: 'No logo found.');
          else
          res.type('png')
          .sendFile(__dirname + '/uploads/' + data.logo);

          );
          );





          share|improve this answer

























          • Apparently I can't just add setHeader with sendFile, so I do this res.append('Content-Type', 'image/png') res.status(200).sendFile(__dirname + '/uploads/' + data.logo); but still, the image is not being displayed

            – imin
            Nov 15 '18 at 7:31











          • sorry I'm missed something you have to set the type for sendFile, I've edit the response. Also check expressjs.com/en/api.html#res.sendFile

            – cal_br_mar
            Nov 15 '18 at 20:15













          0












          0








          0







          Assuming that you want to pass the school ID to request the image, you don't need axios to make the request, you can use directly the <img src> tag with a dynamic parameter to request the data. You also need to change you express configuration to return the image with Content-Type:'image/png' or whatever is the mime type of your data.



          Then on vue template you will need to pass the school id to the dynamic route, the data request and handling will be done by the img element



          <img :src="`/logo/$schoolID">


          .



          router.get('/logo/:schoolID', function(req, res)
          School.findOne( _id: mongoose.mongo.ObjectId(req.params.schoolID) ).exec().then(function (data)
          if (!data)
          console.log("error... no logo found for the given id: " + req.params.schoolID)
          return res.status(200)
          .send(success: false, msg: 'No logo found.');
          else
          res.type('png')
          .sendFile(__dirname + '/uploads/' + data.logo);

          );
          );





          share|improve this answer















          Assuming that you want to pass the school ID to request the image, you don't need axios to make the request, you can use directly the <img src> tag with a dynamic parameter to request the data. You also need to change you express configuration to return the image with Content-Type:'image/png' or whatever is the mime type of your data.



          Then on vue template you will need to pass the school id to the dynamic route, the data request and handling will be done by the img element



          <img :src="`/logo/$schoolID">


          .



          router.get('/logo/:schoolID', function(req, res)
          School.findOne( _id: mongoose.mongo.ObjectId(req.params.schoolID) ).exec().then(function (data)
          if (!data)
          console.log("error... no logo found for the given id: " + req.params.schoolID)
          return res.status(200)
          .send(success: false, msg: 'No logo found.');
          else
          res.type('png')
          .sendFile(__dirname + '/uploads/' + data.logo);

          );
          );






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 15 '18 at 20:14

























          answered Nov 14 '18 at 18:49









          cal_br_marcal_br_mar

          67638




          67638












          • Apparently I can't just add setHeader with sendFile, so I do this res.append('Content-Type', 'image/png') res.status(200).sendFile(__dirname + '/uploads/' + data.logo); but still, the image is not being displayed

            – imin
            Nov 15 '18 at 7:31











          • sorry I'm missed something you have to set the type for sendFile, I've edit the response. Also check expressjs.com/en/api.html#res.sendFile

            – cal_br_mar
            Nov 15 '18 at 20:15

















          • Apparently I can't just add setHeader with sendFile, so I do this res.append('Content-Type', 'image/png') res.status(200).sendFile(__dirname + '/uploads/' + data.logo); but still, the image is not being displayed

            – imin
            Nov 15 '18 at 7:31











          • sorry I'm missed something you have to set the type for sendFile, I've edit the response. Also check expressjs.com/en/api.html#res.sendFile

            – cal_br_mar
            Nov 15 '18 at 20:15
















          Apparently I can't just add setHeader with sendFile, so I do this res.append('Content-Type', 'image/png') res.status(200).sendFile(__dirname + '/uploads/' + data.logo); but still, the image is not being displayed

          – imin
          Nov 15 '18 at 7:31





          Apparently I can't just add setHeader with sendFile, so I do this res.append('Content-Type', 'image/png') res.status(200).sendFile(__dirname + '/uploads/' + data.logo); but still, the image is not being displayed

          – imin
          Nov 15 '18 at 7:31













          sorry I'm missed something you have to set the type for sendFile, I've edit the response. Also check expressjs.com/en/api.html#res.sendFile

          – cal_br_mar
          Nov 15 '18 at 20:15





          sorry I'm missed something you have to set the type for sendFile, I've edit the response. Also check expressjs.com/en/api.html#res.sendFile

          – cal_br_mar
          Nov 15 '18 at 20:15

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53305365%2fvuejs-load-image-from-nodejs-res-sendfile%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          這個網誌中的熱門文章

          Barbados

          How to read a connectionString WITH PROVIDER in .NET Core?

          Node.js Script on GitHub Pages or Amazon S3