Display raw image content-type in vue.js

半腔热情 提交于 2019-12-06 03:33:00

If you already have Buffer of your image you can specify pre-defined link in your client app:

this.urlImg = '/my/url/to/get/dynamic/image';

And define route to send image from server to client (for Express):

server.get("my/url/to/get/dynamic/image", function(req, res) {
   var myBuffer = yourFunctionReturnsBuffer();
   res.writeHead(200, {
    'Content-Type': 'image/jpeg',
    'Content-Length': myBuffer.length
   });
   res.end(myBuffer); 
 });

Working example for Express+request: My Gist

UPDATE

Load image in browser via ajax (example below). But it is not possible to send request body for GET method with native browser XMLHttpRequest object (this is base for all ajax libraries). From MDN:

send() accepts an optional parameter which lets you specify the request's body; this is primarily used for request such as PUT. If the request method is GET or HEAD, the body parameter is ignored and request body is set to null.

var app = new Vue({
    el: "#app",
    data: {
        // empty image
        src: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
    },
    created() {
        let config = {
            // example url
            url: 'https://www.gravatar.com/avatar/7ad5ab35f81ff2a439baf00829ee6a23',
            method: 'GET',
            responseType: 'blob'
        }
        axios(config)
          .then((response) => {
              let reader = new FileReader();
              reader.readAsDataURL(response.data); 
              reader.onload = () => {
                  this.src = reader.result;
              }
          });
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<div id="app">
  <img :src="src" alt="">
</div>

UPDATE 2

Decode image as array buffer

var app = new Vue({
    el: "#app",
    data: {
        // empty image
        src: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
    },
    created() {
        let config = {
            // example url
            url: 'https://www.gravatar.com/avatar/7ad5ab35f81ff2a439baf00829ee6a23',
            method: 'GET',
            responseType: 'arraybuffer'
        }
        axios(config)
          .then((response) => {
              var bytes = new Uint8Array(response.data);
              var binary = bytes.reduce((data, b) => data += String.fromCharCode(b), '');
              this.src = "data:image/jpeg;base64," + btoa(binary);
          });
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<div id="app">
  <img :src="src" alt="">
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!