Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

Requirement: the backend interface returns a document stream format image, how to display and preview it on the page?

Ideas:

  • Set axios responseType to ‘blob’; Portal: JavaScript Blob objects in detail
  • Url.createobjecturl () creates a DOMString with a URL representing the object given in the argument;
  • Preview via the Image component in Element-UI;

Complete code:

<template>
  <div class="home">
    <el-image 
      style="width: 200px; height: 200px"
      :src="imgUrl" 
      :preview-src-list="srcList">
    </el-image>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  data(){
    return{
      imgUrl:' '.srcList: []}},methods: {loadFile() {
      axios({
        method: 'get'.url: '/api/file/download/123456'.responseType: 'blob'.params: {},
        headers: {
          Accept: 'application/octet-stream'.token: myToken,   // Get the token, which assumes myToken
        },
      }).then(res= > {
        let blob = new Blob([res.data], {type: 'image/jpeg'});
        const imageUrl = URL.createObjectURL(blob);
        this.imgUrl = imageUrl;
        this.srcList.push(imageUrl);
      }).catch(err= > {
        console.log('Export failed')})}},mounted(){
    this.loadFile(); }}</script>
Copy the code

Development:

The url.createObjecturl () static method creates a DOMString with a URL representing the object given in the argument. The lifecycle of this URL and the Document binding in the window that created it. This new URL object represents the specified File object or Blob object.

Note: This feature is available in Web Workers; Note: This feature is not available in Service workers because it can cause memory leaks;

Syntax: objectURL = url.createObjecturl (object); Parameter: object Is used to create a URL File object, Blob object, or MediaSource object; Return value: A DOMString contains an object URL that can be used to specify the contents of the source object.Copy the code

Related links: Vue implementation of file stream download