微信小程序没有预览接口,使用cos-wx-sdk-v5进行预览

1. npm i cos-js-sdk-v5 安装包,使用时微信小程序有警告,安装成功之后记得构建

2.直接进入GitHub 复制文件 ,地址:GitCode - 全球开发者的开源社区,开源代码托管平台

 需要复制的文件路径:demo/lib/cos-wx-sdk-v5.js 

 3.utils 直接新建文件夹,(代码在合力小程序heli_dev 分支)

//GitHub地址:https://gitcode.com/gh_mirrors/co/cos-wx-sdk-v5/blob/master/demo/lib/cos-wx-sdk-v5.js

4. npm i pako  安装pako 包

直接 在utils文件夹中 引用 :import pako from 'pako'


import pako from 'pako'

//引入重写的gzip解压方式
const polyfill = require('./base64');
const {atob} = polyfill;


const uncompress = (resData) => {
  const strData = atob(resData);
  const charData = strData.split('').map(function (x) {
    return x.charCodeAt(0);
  });
  const binData = new Uint8Array(charData);
  const data = pako.inflate(binData);
  return Utf8ArrayToStr(data);
}


const Utf8ArrayToStr = (array) => {
  let out, i, c;
  let char2, char3;

  out = '';
  const len = array.length;
  i = 0;
  while (i < len) {
    c = array[i++];
    switch (c >> 4) {
      case 0:
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
      case 7:
        // 0xxxxxxx
        out += String.fromCharCode(c);
        break;
      case 12:
      case 13:
        // 110x xxxx   10xx xxxx
        char2 = array[i++];
        out += String.fromCharCode(((c & 0x1f) << 6) | (char2 & 0x3f));
        break;
      case 14:
        // 1110 xxxx  10xx xxxx  10xx xxxx
        char2 = array[i++];
        char3 = array[i++];
        out += String.fromCharCode(
          ((c & 0x0f) << 12) | ((char2 & 0x3f) << 6) | ((char3 & 0x3f) << 0),
        );
        break;
    }
  }
  return JSON.parse(out);
}

module.exports = {
  uncompress
}

5. 创建 base64文件夹,重写 gzip 解压,要不然项目上线不能回显图片

 

(function(f) {

    'use strict';
  
    /* istanbul ignore else */
    if (typeof exports === 'object' && exports != null &&
        typeof exports.nodeType !== 'number') {
      module.exports = f ();
    } else if (typeof define === 'function' && define.amd != null) {
      define ([], f);
    } else {
      var base64 = f ();
      var global = typeof self !== 'undefined' ? self : $.global;
      if (typeof global.btoa !== 'function') global.btoa = base64.btoa;
      if (typeof global.atob !== 'function') global.atob = base64.atob;
    }
  
  } (function() {
  
    'use strict';
  
    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  
    function InvalidCharacterError(message) {
      this.message = message;
    }
    InvalidCharacterError.prototype = new Error ();
    InvalidCharacterError.prototype.name = 'InvalidCharacterError';
  
    // encoder
    // [https://gist.github.com/999166] by [https://github.com/nignag]
    function btoa(input) {
      var str = String (input);
      for (
        // initialize result and counter
        var block, charCode, idx = 0, map = chars, output = '';
        // if the next str index does not exist:
        //   change the mapping table to "="
        //   check if d has no fractional digits
        str.charAt (idx | 0) || (map = '=', idx % 1);
        // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
        output += map.charAt (63 & block >> 8 - idx % 1 * 8)
      ) {
        charCode = str.charCodeAt (idx += 3 / 4);
        if (charCode > 0xFF) {
          throw new InvalidCharacterError ("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
        }
        block = block << 8 | charCode;
      }
      return output;
    }
  
    // decoder
    // [https://gist.github.com/1020396] by [https://github.com/atk]
    function atob(input) {
      var str = (String (input)).replace (/[=]+$/, ''); // #31: ExtendScript bad parse of /=
      // if (str.length % 4 === 1) {
      //   throw new InvalidCharacterError ("'atob' failed: The string to be decoded is not correctly encoded.");
      // }
      for (
        // initialize result and counters
        var bc = 0, bs, buffer, idx = 0, output = '';
        // get next character
        buffer = str.charAt (idx++); // eslint-disable-line no-cond-assign
        // character found in table? initialize bit storage and add its ascii value;
        ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
          // and if not first of each 4 characters,
          // convert the first 8 bits to one ascii character
          bc++ % 4) ? output += String.fromCharCode (255 & bs >> (-2 * bc & 6)) : 0
      ) {
        // try to find character in table (0-63, not found => -1)
        buffer = chars.indexOf (buffer);
      }
      return output;
    }
  
    return {btoa: btoa, atob: atob};
  
  }));
  
  

 5. 在回显 图片时使用方法

返回的上传 数据

import Api from "../../../utils/api"
import Request from '../../../utils/request'
var COS = require('../../../utils/cos-wx-sdk-v5.js')
// 直接引入cos-js-sdk-v5 会出现警告
// import COS from 'cos-js-sdk-v5'  
import {
    uncompress
} from "../../../utils/util"

// a4de829452484c58b4935a632c3cc1ff 文件的 batchId
this.queryFileList('a4de829452484c58b4935a632c3cc1ff')

  queryFileList(data) {
        const that = this
        let files = []
        // const data = 'a4de829452484c58b4935a632c3cc1ff'
        Request.post(Api.queryFileList + "/" + data).then((res) => {
               // res.data 获取的文件信息 数组
            wx.hideLoading()
            if (res.code == 0) {
                res.data.forEach(file => {
                    const keyInfo = uncompress(file.keyJson);
                    if (keyInfo) {
                        const cos = new COS({
                            SecretId: keyInfo.cos.secretId,
                            SecretKey: keyInfo.cos.secretKey,
                        });
                       
                        cos.getObjectUrl(
                            {
                                Bucket: keyInfo.cos.bucketName[file.isPublic],
                                Region: keyInfo.cos.region,
                                Key: file.url,
                            },
                            function (err, data) {
                                if (!err) {
                                    /* url为对象访问 url */
                                    const url = data.Url;
                                    /* 复制 downloadUrl 的值到浏览器打开会自动触发下载 */
                                    const filename = file.name.replaceAll(' ', '').replaceAll('&', '-');
                                    const downloadUrl =
                                        url +
                                        (url.indexOf('?') > -1 ? '&' : '?') +
                                        'response-content-disposition=attachment;filename="' +
                                        filename +
                                        '"'; // 补充强制下载的参数
                                    // vant 组件 opload 的回显
                                    files.push({
                                        url: downloadUrl,
                                        isImage: true
                                    })
                                    //
                                    that.setData({
                                        fileList: files
                                    })

                                } else {
                                    console.log('预览失败');
                                }
                            },
                        );
                    }
                })

            }
        }).catch(() => {
            wx.hideLoading()
        })
    },

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值