Explore how front-end images carry tokens for verification

foreword

Images play an important role in front-end development. They are not only aesthetic elements, but also convey information and stimulate user interest. With the increase of application scenarios, front-end developers need to carry verification information during the image loading process. Such as token , used for identity verification, permission control, etc. Secure transmission of image information is achieved by carrying token information in the image URL or request header .


Implementation ideas

  1. Create a tokenImgcomponent named which is used to display pictures and support preview function;
  2. In the component's template, use <img>the tag to display the image, or use element-uithe <el-image>tag to preview the image;
  3. In the properties of the component, receive the image URLaddress ( imgUrl), image type ( imgType), image width ( width) and height ( height);
  4. In the data of the component, define the preview picture list ( previewList) and the preview picture path ( previewpath);
  5. Implement two methods viewModel()and preViewModel()for previewing pictures only and previewing with thumbnails respectively;
  6. In the method, assign the image to the tag's attribute viewModel()by calling the downloaded file API (downloadFileApi)and creating an object based on the returned file content ;URLURL<img>src
  7. In preViewModel()the method, also call the downloaded file API, create URLan object with the returned file content, and URLadd it to the preview image list;
  8. Use to watchmonitor the change of the property, and call the corresponding method imgUrlaccording to the value of the property when it changes ;imgType
  9. In the hook of the component , call the corresponding method mounted()according to the initial property value;imgType
  10. Register the component as a global component in main.jsthe file tokenImgfor use elsewhere;
  11. Where you need to use this component, use <TokenImg>the tag and pass the corresponding attributes (such as picture URL, picture type, width and height); in this way, you can use the component
    in the front end to display pictures with and support the preview function. Take care to make sure you pass the correct image , type, width and height when using the component .tokenImgTokenURL

package file

<template>
  <div>
    <!-- 显示图片 -->
    <img ref="img" :style="{width:width,height:height}" v-if="imgType == 'view'" />
    <!-- 使用element-ui的el-image进行图片预览 -->
    <el-image :style="{width:width,height:height}" ref="previewimg" v-if="imgType == 'preView'" :src="previewpath"
      :preview-src-list="previewList"></el-image>
  </div>
</template>
<script>
// 引入的接口文件
import {
      
       downloadFileApi } from "@/api/publicApi/enumeration";
export default {
      
      
  name: "token-img",
  props: {
      
      
    // 图片的URL地址
    imgUrl: {
      
      
      type: String,
    },
    // 图片类型,可选为'view'(仅预览图片)或'preView'(可点击预览)
    imgType: {
      
      
      type: String,
      default: "view",
    },
    // 图片的宽度
    width: {
      
      
      type: String,
    },
    // 图片的高度
    height: {
      
      
      type: String,
    },
  },
  data() {
      
      
    return {
      
      
      // 预览图片列表
      previewList: [],
      // 预览图片路径
      previewpath: "",
    };
  },
  methods: {
      
      
    //仅预览图片
    viewModel() {
      
      
      const img = this.$refs.img;
      // 调用下载文件的API并根据返回的文件内容创建URL对象
      downloadFileApi(this.imgUrl).then((res) => {
      
      
        img.src = URL.createObjectURL(res);
        img.onload = () => {
      
      
          URL.revokeObjectURL(img.src);
        };
      });
    },
    //带缩略图预览
    preViewModel() {
      
      
      downloadFileApi(this.imgUrl).then((res) => {
      
      
        // 调用下载文件的API并根据返回的文件内容创建URL对象
        this.previewpath = URL.createObjectURL(res);
        this.previewList.push(this.previewpath);
      });
    },
  },
  watch: {
      
      
    // 监听imgUrl变化
    imgUrl() {
      
      
      if (this.imgType == "view") {
      
      
        this.viewModel();
      } else if (this.imgType == "preView") {
      
      
        this.preViewModel();
      }
    },
  },
  mounted() {
      
      
    if (this.imgType == "view") {
      
      
      this.viewModel();
    } else if (this.imgType == "preView") {
      
      
      this.preViewModel();
    }
  },
};
</script>

imported interface file

export function downloadFileApi(imgUrl) {
    
    
  return request({
    
    
    url: "/api/file/examine-preview"+imgUrl,
    method: "get",
    responseType: "blob",
  });
}

main.js

// 将其注册为全局组件
import TokenImg from "@/components/tokenImg";
Vue.component('TokenImg', TokenImg)

use file

<TokenImg :width="`50px`" :height="`50px`" :imgUrl="YourUrl" :imgType="`preView`"/>

achieve effect

make a request

insert image description here

render view

insert image description here


expand

1. Implement this operation in the WeChat applet

Package file ----.js

// 引入服务器请求封装的模块
const server = require('../../utils/server.js');

Component({
    
    
  // 组件的内部数据
  data: {
    
    
    previewPath: "", // 预览图片路径
  },
  // 组件的对外属性,是属性名到属性设置的映射表
  properties: {
    
    
    imgUrl: {
    
     // 图片的URL地址
      type: String,
    },
    imageWidth: {
    
     // 图片的宽度
      type: String,
    },
    imageHeight: {
    
     // 图片的高度
      type: String,
    },
  },
  // 组件的生命周期函数
  lifetimes: {
    
    
    attached() {
    
     // 组件实例进入页面节点树时执行
      this.fetchData(); // 调用数据处理方法
    },
  },
  // 组件的方法,包括事件响应函数和任意的自定义方法
  methods: {
    
    
    // 发起请求获取图片数据
    fetchData() {
    
    
      const {
    
     imgUrl } = this.properties; // 解构获取图片URL
      const url = `http://192.168.0.11:8888/api/api-file/file/downloadFile/file-fld/${
      
      imgUrl}`; // 拼接请求URL
      server.request({
    
    
        url, // 请求图片的URL
        responseType: 'arraybuffer', // 响应类型为数组缓冲区
        success: (res) => {
    
     // 请求成功的回调函数
          const base64 = wx.arrayBufferToBase64(res.data); // 将数组缓冲区转换为base64编码
          const imageUrl = `data:image/png;base64,${
      
      base64}`; // 拼接base64编码的图片URL
          this.setData({
    
     // 更新组件的数据
            previewPath: imageUrl
          });
        }
      });
    },
    // 点击预览图片
    previewImageOn(e) {
    
    
      const {
    
     previewpath } = e.target.dataset; // 解构获取预览图片URL
      wx.previewImage({
    
     // 调用微信预览图片的API
        urls: [previewpath], // 需要预览的图片URL列表
      });
    },
  }
});

Package file ----.wxml

<view>
   <!-- 使用小程序的image组件进行图片预览 -->
   <image bindtap="previewImageOn" data-previewPath="{
     
     {previewPath}}" src="{
     
     {previewPath}}" mode="aspectFill" 
   style="width:{ 
        { 
        imageWidth}};height:{ 
        { 
        imageHeight}};" />
</view>

app.jsonGlobal import

"usingComponents": {
    
    
  "token-img": "./components/tokenImg/tokenImg"
},

page.jsonGlobal import

{
    
    
    "usingComponents": {
    
    
        "token-img": "./components/tokenImg/tokenImg"
    }
}

use file

<view>
    <token-img imageWidth="100%" imageHeight="180rpx" imgUrl="{
     
     {YourUrl}}"></token-img>
</view>

achieve effect

insert image description here


2. Download the file with the token

The first way: handwritten implementation

//下载方法
getBgdzByGcsj(row) {
    
    
  // 通过接口下载文件
  downloadFileApiDown(row.bgdz).then((res) => {
    
    
    // 将文件流转换为下载链接
    const downloadUrl = URL.createObjectURL(res);
    // 创建一个<a>标签
    const link = document.createElement("a");
    // 设置链接的URL为下载链接
    link.href = downloadUrl;
    // 设置下载的文件名为"报表管理.xls"
    link.download = "报表管理.xls";
    // 隐藏<a>标签
    link.style.display = "none";
    // 将<a>标签添加到页面的<body>中
    document.body.appendChild(link);
    // 触发<a>标签的点击事件,开始下载
    link.click();
    // 下载完成后删除<a>标签
    document.body.removeChild(link);
  });
}

The second way: using plugin( file-saver)

file-saver is a JavaScriptlibrary for saving files in the browser. It provides an easy way to generate and save files without server involvement. Using file-saverthe plugin, you can easily generate and download files on the front end without sending file requests to the server and returning file links, which greatly simplifies the file download process.

file-saverThe main function of the plug-in is to Blobsave the file download link generated by the object to the download path of the browser. It provides the following methods:

1. saveAsMethod

Save the file locally. You can use saveAsthe method to specify the content and name of the file, and then save it to the browser's download path.

2. saveMethod

Save the file locally, saveAssimilar to the method, but the file save dialog box will not pop up.

3. createObjectURLMethod

Create Blobobject URL. With createObjectURLthe method, you can Blobconvert the object to be available for download URL.

4. revokeObjectURLMethod

Created before release URL. Once the file download is complete, you can use revokeObjectURLthe method to free the created one URLto release browser resources.

  • Install

    npm install file-saver
    
  • introduce

    import {
          
           saveAs } from 'file-saver';
    
  • use

    // res 返回地址
    saveAs(res, '报表管理.xls');
    

Guess you like

Origin blog.csdn.net/Shids_/article/details/131851632