在vue.js中显示原始图像内容类型 [英] Display raw image content-type in vue.js

查看:151
本文介绍了在vue.js中显示原始图像内容类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过带有请求正文的HTTP GET从REST API中检索图像。

I am retrieving an image from a REST API via an HTTP GET with a request body.

通过此测试,我设法使用 node.js chai.js

I've managed to check the returned content via this test using node.js and chai.js:

      expect(res).to.have.header('Content-Type', 'image/jpeg');
      expect(res).to.have.header('Access-Control-Allow-Origin', '*');
      expect(res).to.have.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization');
      expect(res).to.have.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
      expect(res).to.have.status(200);
      expect(res.body).to.be.instanceof(Buffer); // the image content

vue.js 文件我曾用来将图像附加到< img ...> HTML标记中,如下所示:

In the vue.js file I was used to attach an image to an <img ...> HTML tag like this:

<img v-bind:src="urlImg">

然后在javascript部分中指定如下网址:

Then specifying in the javascript part the URL like this:

# this string representing the URL is returned by a function
this.urlImg = 'http://example.com/my_img.jpeg' 

但在这种情况下,我无法提供URL,因为HTTP GET期望正文返回带有内容类型图片/ jpeg

but in this case I am not able to provide the URL because the HTTP GET is expecting a body to return the image with content type image/jpeg.

我什至不确定这是否可行,并且我可能会误认为内容类型 image / jpeg 应该如何去工作。如何在 vue.js 中执行此操作?有可能吗?像Postman(Chrome应用程序)之类的东西一样,有没有办法检查此HTTP响应的图像内容,我无法检查假装将其视为text / Json的响应。

I am not even sure this is possible and I may be misunderstanding how the content type image/jpeg is supposed to work. How do I do this in vue.js? Is it possible at all? Is there a way to check the image content of this HTTP response as with stuff like Postman (Chrome app) I can not inspect the response pretending to treat it as text/Json.

编辑

关于已接受的答案:最近提出的解决方案( UPDATE 2 )为我工作(使用HTTP POST,为请求提供JSON正文)。确保使用 axios https://github.com / axios / axios )执行HTTP请求(您可以将其导入Vue文件的< script> 部分,如下所示:从 axios导入axios; )。

Regarding the accepted answer: the last proposed solution (UPDATE 2) worked for me (using HTTP POST providing a JSON body for the request). Make sure you use axios (https://github.com/axios/axios) to perform the HTTP requests (you can import it in the <script> part of the Vue file like this: import axios from "axios";).

我正在使用 vue-resource https://github.com/pagekit/vue-resource ),假装它与 axios 相同,

I was using vue-resource (https://github.com/pagekit/vue-resource) pretending it was the same as axios, but it is not and it took me a while to realize it.

推荐答案

如果您已经有 Buffer 您可以在客户端应用中指定预定义的链接:

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';

并定义从服务器向客户端发送图像的路径(对于Express):

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); 
 });

Express + request的工作示例:我的要旨

Working example for Express+request: My Gist

更新

通过ajax在浏览器中加载图像(下面的示例)。但是不可能使用本地浏览器XMLHttpRequest对象发送GET方法的请求主体(这是所有ajax库的基础)。在MDN中:

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()接受一个可选参数,可用于指定请求的正文;这主要用于请求(例如PUT)。如果请求方法是 GET HEAD ,则 body参数将忽略 ,并且请求正文设置为null。

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>

更新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>

这篇关于在vue.js中显示原始图像内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆