PHP群:95885625 Hbuilder+MUI群:81989597 站长QQ:634381967
    您现在的位置: 首页 > 开发编程 > HBuilderX教程 > 正文

    uniapp上传图片、视频到oss

    作者:admin来源:网络浏览:时间:2020-10-06 10:53:47我要评论
    导读:uniapp上传图片、视频到oss,阿里云oss js签名直传的方式。示例代码如下:
    阿里云oss  js签名直传的方式。示例代码如下:

    1.上传图片

    1. <template> 
    2.     <view class="zyby-img-upload-common auth-img-item" :class="{'img-item-special': !imgUrl}"
    3.         <div v-if="!imgUrl" @tap="ChooseImage" class='flex-perfect-center'
    4.             <slot name="image"
    5.                 <image src="/static/img/btn_data_upload.png"></image> 
    6.             </slot> 
    7.             <div class="text-desc"
    8.                 <slot>上传图片</slot> 
    9.             </div> 
    10.         </div> 
    11.         <img class="exist-img" v-else :src="imgUrl" @tap="ChooseImage"
    12.         <!-- <progress class="upload-progress" v-if="progress > 0" :percent="progress" active stroke-width="3"></progress> --> 
    13.         <img class="img-delete" v-if="imgUrl && deleteFlag" src="/static/icon_img/icn_delete.png" @tap="DelImg"
    14.     </view> 
    15. </template> 
    16.  
    17. <script> 
    18.     import OSSUtil from '../libs/ossUtil.js' 
    19.     export default { 
    20.         name: 'byImgUpload'
    21.         props: { 
    22.             authId: String, 
    23.             imgUrl: String, 
    24.             deleteFlag: Boolean, 
    25.             startShowAction: Function, 
    26.             startDelete: Function, 
    27.             imgActions: Array 
    28.         }, 
    29.         data() { 
    30.             return { 
    31.                 progress: 0, 
    32.                 imgData: { 
    33.                     visible: false
    34.                     actions: this.imgActions 
    35.                 } 
    36.             } 
    37.         }, 
    38.         methods: { 
    39.             async ChooseImage() { 
    40.                 let files = await OSSUtil.getImage(); // 选择图片 
    41.                 let sign = await OSSUtil.get_STS() // 获取签名等信息 
    42.  
    43.                 let imageSrc = files.tempFilePaths[0]; 
    44.                 let fileName = OSSUtil.getFileName(imageSrc); // 自定义上传后的文件名称 
    45.                  
    46.                 let uploadTask = uni.uploadFile({ 
    47.                     url: sign.host, 
    48.                     filePath: imageSrc, 
    49.                     fileType: 'image'
    50.                     name: 'file'
    51.                     formData: { 
    52.                         name: imageSrc, 
    53.                         'key': fileName, 
    54.                         'policy': sign.policy, 
    55.                         'OSSAccessKeyId': sign.accessId, 
    56.                         'success_action_status''200'
    57.                         //让服务端返回200,不然,默认会返回204 
    58.                         'signature': sign.signature, 
    59.                     }, 
    60.                     success: (res) => { 
    61.                         console.log('uploadImage success, res is:', res) 
    62.                         uni.showToast({ 
    63.                             title: '上传成功'
    64.                             icon: 'success'
    65.                             duration: 1000 
    66.                         }); 
    67.                         this.$emit('imgUploaded', {data: sign.host + fileName, authId: this.authId}); 
    68.                     }, 
    69.                     fail: (err) => { 
    70.                         console.log('uploadImage fail', err); 
    71.                         uni.showModal({ 
    72.                             content: err.errMsg, 
    73.                             showCancel: false 
    74.                         }); 
    75.                     } 
    76.                 }); 
    77.                 uploadTask.onProgressUpdate((res) => { 
    78.                     console.log("上传进度" + res.progress); 
    79.                     this.progress = res.progress; 
    80.                 }); 
    81.  
    82.                 // this.$emit('imgUploaded', {data: files.tempFilePaths[0], authId: this.authId}); 
    83.             }, 
    84.             ViewImage(e) { 
    85.                 uni.previewImage({ 
    86.                     urls: this.imgList, 
    87.                     current: e.currentTarget.dataset.url 
    88.                 }); 
    89.             }, 
    90.             DelImg() { 
    91.                 this.$emit('imgDel', { 
    92.                     authId: this.authId 
    93.                 }); 
    94.             }, 
    95.         } 
    96.     } 
    97. </script> 
    98.  
    99. <!-- Add "scoped" attribute to limit CSS to this component only --> 
    100. <style scoped lang="less" rel="stylesheet/less"
    101.     @import "../style/function.less"
    102.     @import "../style/variable.less"
    103.  
    104.     .zyby-img-upload-common { 
    105.         height: 450rpx; 
    106.         width: 100%; 
    107.         margin-top: 26rpx; 
    108.     } 
    109.  
    110.     .auth-img-item { 
    111.         position: relative; 
    112.  
    113.         >div:first-child { 
    114.             height: 100%; 
    115.             flex-direction: column; 
    116.  
    117.             image { 
    118.                 .square-hw(46) 
    119.             } 
    120.  
    121.             .text-desc { 
    122.                 margin-top: 20rpx; 
    123.                 font-family: PingFangSC-Regular; 
    124.                 font-size: 26rpx; 
    125.                 color: @base-finish-color-deep; 
    126.             } 
    127.         } 
    128.  
    129.         .exist-img { 
    130.             width: 100%; 
    131.             height: 100%; 
    132.         } 
    133.  
    134.         .upload-progress { 
    135.             position: absolute; 
    136.             bottom: 0; 
    137.             right: 0; 
    138.             left: 0; 
    139.         } 
    140.  
    141.         .img-delete { 
    142.             .square-hw(36); 
    143.             position: absolute; 
    144.             top: 10rpx; 
    145.             right: 10rpx; 
    146.         } 
    147.     } 
    148.  
    149.     .img-item-special { 
    150.         border: 1px dashed #13DBBF; 
    151.         /*no*/ 
    152.         border-radius: 6rpx; 
    153.         /*no*/ 
    154.     } 
    155. </style> 


    上传视频代码如下:
     

    1. <template> 
    2.   <view class="zyby-img-upload-common auth-img-item" :class="{'img-item-special': !videoUrl}"
    3.     <div v-if="!videoUrl"  @tap="ChooseVideo" class='flex-perfect-center'
    4.       <slot name="image"><image src="/static/img/btn_data_upload.png"></image></slot> 
    5.       <div class="text-desc"><slot>上传视频</slot></div> 
    6.     </div> 
    7.      <video class="exist-img" controls v-else :src="videoUrl"></video> 
    8.                     <!-- <video class="exist-img" src="https://dcloud-img.oss-cn-hangzhou.aliyuncs.com/guide/uniapp/%E7%AC%AC1%E8%AE%B2%EF%BC%88uni-app%E4%BA%A7%E5%93%81%E4%BB%8B%E7%BB%8D%EF%BC%89-%20DCloud%E5%AE%98%E6%96%B9%E8%A7%86%E9%A2%91%E6%95%99%E7%A8%8B@20181126.mp4" 
    9.                                    @error="videoErrorCallback" controls v-else :src="videoUrl"></video> --> 
    10.     <progress class="upload-progress" v-if="progress > 0" :percent="progress" active stroke-width="3"></progress> 
    11.     <img class="img-delete" v-if="videoUrl && deleteFlag" src="/static/icon_img/icn_delete.png" @tap="DelImg"
    12.   </view> 
    13. </template> 
    14.  
    15. <script> 
    16.   import OSSUtil from '../libs/ossUtil.js' 
    17.  
    18.   export default { 
    19.     props: { 
    20.       authId: String, 
    21.       videoUrl: String, 
    22.       deleteFlag: Boolean, 
    23.     }, 
    24.     data () { 
    25.       return { 
    26.           progress: 0, 
    27.         imgData: { 
    28.           visible: false
    29.           actions: this.imgActions 
    30.         } 
    31.       } 
    32.     }, 
    33.     methods: { 
    34.         async ChooseVideo() { 
    35.             let imageSrc = await OSSUtil.getVideo(); 
    36.             let sign = await OSSUtil.get_STS() 
    37.          
    38.             let fileName = OSSUtil.getFileName(imageSrc); 
    39.              
    40.             let uploadTask = uni.uploadFile({ 
    41.                 url: sign.host, 
    42.                 filePath: imageSrc, 
    43.                 fileType: ''
    44.                 name: 'file'
    45.                 formData: { 
    46.                     name: imageSrc, 
    47.                     'key': fileName, 
    48.                     'policy': sign.policy, 
    49.                     'OSSAccessKeyId': sign.accessId, 
    50.                     'success_action_status''200'
    51.                     //让服务端返回200,不然,默认会返回204 
    52.                     'signature': sign.signature, 
    53.                 }, 
    54.                 success: (res) => { 
    55.                     console.log('res:', res) 
    56.                     uni.showToast({ 
    57.                         title: '上传成功'
    58.                         icon: 'success'
    59.                         duration: 1000 
    60.                     }); 
    61.                     this.$emit('videoUploaded', {data: sign.host + fileName, authId: this.authId}); 
    62.                 }, 
    63.                 fail: (err) => { 
    64.                     uni.showModal({ 
    65.                         content: err.errMsg, 
    66.                         showCancel: false 
    67.                     }); 
    68.                 } 
    69.             }); 
    70.             uploadTask.onProgressUpdate((res) => { 
    71.                 console.log("上传进度" + res.progress); 
    72.                 this.progress = res.progress; 
    73.             }); 
    74.          
    75.             // this.$emit('imgUploaded', {data: files.tempFilePaths[0], authId: this.authId}); 
    76.         } 
    77.     }     
    78.   } 
    79. </script> 
    80.  
    81. <!-- Add "scoped" attribute to limit CSS to this component only --> 
    82. <style scoped lang="less" rel="stylesheet/less"
    83.   @import "../style/function.less"
    84.   @import "../style/variable.less"
    85.  
    86.   .zyby-img-upload-common { 
    87.     height: 450rpx; 
    88.     width: 100%; 
    89.     margin-top: 26rpx; 
    90.   } 
    91.   .auth-img-item { 
    92.     position: relative; 
    93.     > div:first-child { 
    94.         height: 100%; 
    95.         flex-direction: column; 
    96.         image { 
    97.         .square-hw(46) 
    98.         } 
    99.         .text-desc { 
    100.           margin-top: 20rpx; 
    101.           font-family: PingFangSC-Regular; 
    102.           font-size: 26rpx; 
    103.           color: @base-finish-color-deep; 
    104.         } 
    105.     } 
    106.     .exist-img { 
    107.         width: 100%; 
    108.         height: 100%; 
    109.       } 
    110.       .upload-progress { 
    111.           position: absolute; 
    112.           bottom: 0; 
    113.           right: 0; 
    114.           left: 0; 
    115.       } 
    116.     .img-delete { 
    117.       .square-hw(36); 
    118.       position: absolute; 
    119.       top: 10rpx; 
    120.       right: 10rpx; 
    121.     } 
    122.   } 
    123.   .img-item-special { 
    124.     border: 1px dashed #13DBBF;/*no*/ 
    125.     border-radius: 6rpx;/*no*/ 
    126.   } 
    127. </style> 




    2.ossUtil.js 相关代码
     

    1. import Crypto from '@/libs/crypto/crypto.js'
    2.     import '@/libs/crypto/hmac.js'
    3.     import '@/libs/crypto/sha1.js'
    4.     import { 
    5.         Base64 
    6.     } from '@/libs/crypto/base64.js'
    7.     import config from '@/config/index.js' 
    8.  
    9.     const uploadFileSize = 1024 * 1024 * 100; // 上传文件的大小限制100m 
    10.     const accesskey = '***************'// 自己去申请 
    11.     const accessId = '*****************' // 自己去申请 
    12.  
    13.     export default { 
    14.         _getPolicy() { 
    15.             let policyText = { 
    16.                 "expiration""2022-01-01T12:00:00.000Z"//设置该Policy的失效时间,超过这个失效时间之后,就没有办法通过这个policy上传文件了 
    17.                 "conditions": [ 
    18.                     ["content-length-range", 0, uploadFileSize] // 设置上传文件的大小限制 
    19.                 ] 
    20.             }; 
    21.  
    22.             return Base64.encode(JSON.stringify(policyText)) 
    23.         }, 
    24.         _getSignature(message) { 
    25.             let bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { 
    26.                 asBytes: true 
    27.             }); 
    28.             return Crypto.util.bytesToBase64(bytes); 
    29.         }, 
    30.         _getSuffix(filename) { 
    31.             let pos = filename.lastIndexOf('.'
    32.             let suffix = '' 
    33.             if (pos != -1) { 
    34.                 suffix = filename.substring(pos) 
    35.             } 
    36.             return suffix; 
    37.         }, 
    38.         getFileName(filename) { 
    39.             console.log('filename:', filename) 
    40.             return 'wx_img/' + new Date().getTime() + Math.random().toString(36).substring(3, 20) + this._getSuffix(filename) 
    41.         }, 
    42.         getImage() { 
    43.             return new Promise((resolve, reject) => { 
    44.                 uni.chooseImage({ 
    45.                     count: 1, //默认9 
    46.                     sizeType: ['original''compressed'], //可以指定是原图还是压缩图,默认二者都有 
    47.                     sourceType: ['album''camera'], 
    48.                     success: (res) => { 
    49.                         resolve(res) 
    50.                     } 
    51.                 }) 
    52.             }); 
    53.         }, 
    54.         getVideo() { 
    55.             return new Promise((resolve, reject) => { 
    56.                 uni.chooseVideo({ 
    57.                     count: 1, 
    58.                     sourceType: ['camera''album'], 
    59.                     success: function(res) { 
    60.                         if (res.size > uploadFileSize) { 
    61.                             uni.showToast({ 
    62.                                 title: '文件大小超过系统上传限制:' + uploadFileSize, 
    63.                                 icon: 'none'
    64.                                 duration: 1000 
    65.                             }); 
    66.                             return
    67.                         } 
    68.                         resolve(res.tempFilePath) 
    69.                     }, 
    70.                     fail: () => { 
    71.                         uni.showToast({ 
    72.                             title: '取消选择视频'
    73.                             icon: 'none'
    74.                             duration: 2000 
    75.                         }); 
    76.                     } 
    77.                 }) 
    78.             }); 
    79.         }, 
    80.         // 获取STS签名 
    81.         get_STS() { 
    82.             // 读取接口 
    83.             /* return new Promise((resolve, reject) => { 
    84.                 let name = new Date().getTime() + Math.random(); 
    85.                 let operate = 'uploadImg'; 
    86.                 let that = this; 
    87.                 uni.request({ 
    88.                     method: "GET", 
    89.                     url: "*************", 
    90.                     data: { 
    91.                         name, 
    92.                         operate, 
    93.                         sign: Crypto.MD5(name + operate + "bayinabayin888").toString() 
    94.                     }, 
    95.                     success(res) { 
    96.                         if (res.data.code != 200) { 
    97.                             that.$alert(res.data.message || res.data.msg) 
    98.                         } else { 
    99.                             resolve(res.data.data) 
    100.                         } 
    101.                     }, 
    102.                     error(err) { 
    103.                         reject(err) 
    104.                     } 
    105.                 }) 
    106.             }) */ 
    107.             // 本地获取 
    108.             return new Promise((resolve, reject) => { 
    109.                 let policy = this._getPolicy(); 
    110.                 let res = { 
    111.                     accessId: accessId, 
    112.                     host: config.img.ossDomain,  // 自己去申请 
    113.                     policy, 
    114.                     signature: this._getSignature(policy), 
    115.                 }; 
    116.                 resolve(res) 
    117.             }) 
    118.         }, 
    119.     }; 


    3.crypto.js 代码

     

    1. /*! 
    2.  * Crypto-JS v1.1.0 
    3.  * http://code.google.com/p/crypto-js/ 
    4.  * Copyright (c) 2009, Jeff Mott. All rights reserved. 
    5.  * http://code.google.com/p/crypto-js/wiki/License 
    6.  */ 
    7. // (function(){ 
    8.  
    9. var base64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
    10.  
    11. // Global Crypto object 
    12. // window.Crypto = {}; 
    13. let Crypto = {}; 
    14.  
    15. // Crypto utilities 
    16. var util = Crypto.util = { 
    17.  
    18.     // Bit-wise rotate left 
    19.     rotl: function (n, b) { 
    20.         return (n << b) | (n >>> (32 - b)); 
    21.     }, 
    22.  
    23.     // Bit-wise rotate right 
    24.     rotr: function (n, b) { 
    25.         return (n << (32 - b)) | (n >>> b); 
    26.     }, 
    27.  
    28.     // Swap big-endian to little-endian and vice versa 
    29.     endian: function (n) { 
    30.  
    31.         // If number given, swap endian 
    32.         if (n.constructor == Number) { 
    33.             return util.rotl(n,  8) & 0x00FF00FF | 
    34.                    util.rotl(n, 24) & 0xFF00FF00; 
    35.         } 
    36.  
    37.         // Else, assume array and swap all items 
    38.         for (var i = 0; i < n.length; i++) 
    39.             n[i] = util.endian(n[i]); 
    40.         return n; 
    41.  
    42.     }, 
    43.  
    44.     // Generate an array of any length of random bytes 
    45.     randomBytes: function (n) { 
    46.         for (var bytes = []; n > 0; n--) 
    47.             bytes.push(Math.floor(Math.random() * 256)); 
    48.         return bytes; 
    49.     }, 
    50.  
    51.     // Convert a string to a byte array 
    52.     stringToBytes: function (str) { 
    53.         var bytes = []; 
    54.         for (var i = 0; i < str.length; i++) 
    55.             bytes.push(str.charCodeAt(i)); 
    56.         return bytes; 
    57.     }, 
    58.  
    59.     // Convert a byte array to a string 
    60.     bytesToString: function (bytes) { 
    61.         var str = []; 
    62.         for (var i = 0; i < bytes.length; i++) 
    63.             str.push(String.fromCharCode(bytes[i])); 
    64.         return str.join(""); 
    65.     }, 
    66.  
    67.     // Convert a string to big-endian 32-bit words 
    68.     stringToWords: function (str) { 
    69.         var words = []; 
    70.         for (var c = 0, b = 0; c < str.length; c++, b += 8) 
    71.             words[b >>> 5] |= str.charCodeAt(c) << (24 - b % 32); 
    72.         return words; 
    73.     }, 
    74.  
    75.     // Convert a byte array to big-endian 32-bits words 
    76.     bytesToWords: function (bytes) { 
    77.         var words = []; 
    78.         for (var i = 0, b = 0; i < bytes.length; i++, b += 8) 
    79.             words[b >>> 5] |= bytes[i] << (24 - b % 32); 
    80.         return words; 
    81.     }, 
    82.  
    83.     // Convert big-endian 32-bit words to a byte array 
    84.     wordsToBytes: function (words) { 
    85.         var bytes = []; 
    86.         for (var b = 0; b < words.length * 32; b += 8) 
    87.             bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); 
    88.         return bytes; 
    89.     }, 
    90.  
    91.     // Convert a byte array to a hex string 
    92.     bytesToHex: function (bytes) { 
    93.         var hex = []; 
    94.         for (var i = 0; i < bytes.length; i++) { 
    95.             hex.push((bytes[i] >>> 4).toString(16)); 
    96.             hex.push((bytes[i] & 0xF).toString(16)); 
    97.         } 
    98.         return hex.join(""); 
    99.     }, 
    100.  
    101.     // Convert a hex string to a byte array 
    102.     hexToBytes: function (hex) { 
    103.         var bytes = []; 
    104.         for (var c = 0; c < hex.length; c += 2) 
    105.             bytes.push(parseInt(hex.substr(c, 2), 16)); 
    106.         return bytes; 
    107.     }, 
    108.  
    109.     // Convert a byte array to a base-64 string 
    110.     bytesToBase64: function (bytes) { 
    111.  
    112.         // Use browser-native function if it exists 
    113.         if (typeof btoa == "function"return btoa(util.bytesToString(bytes)); 
    114.  
    115.         var base64 = [], 
    116.             overflow; 
    117.  
    118.         for (var i = 0; i < bytes.length; i++) { 
    119.             switch (i % 3) { 
    120.                 case 0: 
    121.                     base64.push(base64map.charAt(bytes[i] >>> 2)); 
    122.                     overflow = (bytes[i] & 0x3) << 4; 
    123.                     break
    124.                 case 1: 
    125.                     base64.push(base64map.charAt(overflow | (bytes[i] >>> 4))); 
    126.                     overflow = (bytes[i] & 0xF) << 2; 
    127.                     break
    128.                 case 2: 
    129.                     base64.push(base64map.charAt(overflow | (bytes[i] >>> 6))); 
    130.                     base64.push(base64map.charAt(bytes[i] & 0x3F)); 
    131.                     overflow = -1; 
    132.             } 
    133.         } 
    134.  
    135.         // Encode overflow bits, if there are any 
    136.         if (overflow != undefined && overflow != -1) 
    137.             base64.push(base64map.charAt(overflow)); 
    138.  
    139.         // Add padding 
    140.         while (base64.length % 4 != 0) base64.push("="); 
    141.  
    142.         return base64.join(""); 
    143.  
    144.     }, 
    145.  
    146.     // Convert a base-64 string to a byte array 
    147.     base64ToBytes: function (base64) { 
    148.  
    149.         // Use browser-native function if it exists 
    150.         if (typeof atob == "function"return util.stringToBytes(atob(base64)); 
    151.  
    152.         // Remove non-base-64 characters 
    153.         base64 = base64.replace(/[^A-Z0-9+\/]/ig, ""); 
    154.  
    155.         var bytes = []; 
    156.  
    157.         for (var i = 0; i < base64.length; i++) { 
    158.             switch (i % 4) { 
    159.                 case 1: 
    160.                     bytes.push((base64map.indexOf(base64.charAt(i - 1)) << 2) | 
    161.                                (base64map.indexOf(base64.charAt(i)) >>> 4)); 
    162.                     break
    163.                 case 2: 
    164.                     bytes.push(((base64map.indexOf(base64.charAt(i - 1)) & 0xF) << 4) | 
    165.                                (base64map.indexOf(base64.charAt(i)) >>> 2)); 
    166.                     break
    167.                 case 3: 
    168.                     bytes.push(((base64map.indexOf(base64.charAt(i - 1)) & 0x3) << 6) | 
    169.                                (base64map.indexOf(base64.charAt(i)))); 
    170.                     break
    171.             } 
    172.         } 
    173.  
    174.         return bytes; 
    175.  
    176.     } 
    177.  
    178. }; 
    179.  
    180. // Crypto mode namespace 
    181. Crypto.mode = {}; 
    182.  
    183. // })(); 
    184.  
    185. export default Crypto; 

    4.base64.js 代码
     

    1. export const Base64 = { 
    2.  
    3.         // private property 
    4.         _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
    5.  
    6.         // public method for encoding 
    7.         encode : function (input) { 
    8.             var output = ""
    9.             var chr1, chr2, chr3, enc1, enc2, enc3, enc4; 
    10.             var i = 0; 
    11.  
    12.             input = Base64._utf8_encode(input); 
    13.  
    14.             while (i < input.length) { 
    15.  
    16.                 chr1 = input.charCodeAt(i++); 
    17.                 chr2 = input.charCodeAt(i++); 
    18.                 chr3 = input.charCodeAt(i++); 
    19.  
    20.                 enc1 = chr1 >> 2; 
    21.                 enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); 
    22.                 enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); 
    23.                 enc4 = chr3 & 63; 
    24.  
    25.                 if (isNaN(chr2)) { 
    26.                     enc3 = enc4 = 64; 
    27.                 } else if (isNaN(chr3)) { 
    28.                     enc4 = 64; 
    29.                 } 
    30.  
    31.                 output = output + 
    32.                 this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + 
    33.                 this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); 
    34.  
    35.             } 
    36.  
    37.             return output; 
    38.         }, 
    39.  
    40.         // public method for decoding 
    41.         decode : function (input) { 
    42.             var output = ""
    43.             var chr1, chr2, chr3; 
    44.             var enc1, enc2, enc3, enc4; 
    45.             var i = 0; 
    46.  
    47.             input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); 
    48.  
    49.             while (i < input.length) { 
    50.  
    51.                 enc1 = this._keyStr.indexOf(input.charAt(i++)); 
    52.                 enc2 = this._keyStr.indexOf(input.charAt(i++)); 
    53.                 enc3 = this._keyStr.indexOf(input.charAt(i++)); 
    54.                 enc4 = this._keyStr.indexOf(input.charAt(i++)); 
    55.  
    56.                 chr1 = (enc1 << 2) | (enc2 >> 4); 
    57.                 chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); 
    58.                 chr3 = ((enc3 & 3) << 6) | enc4; 
    59.  
    60.                 output = output + String.fromCharCode(chr1); 
    61.  
    62.                 if (enc3 != 64) { 
    63.                     output = output + String.fromCharCode(chr2); 
    64.                 } 
    65.                 if (enc4 != 64) { 
    66.                     output = output + String.fromCharCode(chr3); 
    67.                 } 
    68.  
    69.             } 
    70.  
    71.             output = Base64._utf8_decode(output); 
    72.  
    73.             return output; 
    74.  
    75.         }, 
    76.  
    77.         // private method for UTF-8 encoding 
    78.         _utf8_encode : function (string) { 
    79.             string = string.replace(/\r\n/g,"\n"); 
    80.             var utftext = ""
    81.  
    82.             for (var n = 0; n < string.length; n++) { 
    83.  
    84.                 var c = string.charCodeAt(n); 
    85.  
    86.                 if (c < 128) { 
    87.                     utftext += String.fromCharCode(c); 
    88.                 } 
    89.                 else if((c > 127) && (c < 2048)) { 
    90.                     utftext += String.fromCharCode((c >> 6) | 192); 
    91.                     utftext += String.fromCharCode((c & 63) | 128); 
    92.                 } 
    93.                 else { 
    94.                     utftext += String.fromCharCode((c >> 12) | 224); 
    95.                     utftext += String.fromCharCode(((c >> 6) & 63) | 128); 
    96.                     utftext += String.fromCharCode((c & 63) | 128); 
    97.                 } 
    98.  
    99.             } 
    100.  
    101.             return utftext; 
    102.         }, 
    103.  
    104.         // private method for UTF-8 decoding 
    105.         _utf8_decode : function (utftext) { 
    106.             var string = ""
    107.             var i = 0; 
    108.             var c = c1 = c2 = 0; 
    109.  
    110.             while ( i < utftext.length ) { 
    111.  
    112.                 c = utftext.charCodeAt(i); 
    113.  
    114.                 if (c < 128) { 
    115.                     string += String.fromCharCode(c); 
    116.                     i++; 
    117.                 } 
    118.                 else if((c > 191) && (c < 224)) { 
    119.                     c2 = utftext.charCodeAt(i+1); 
    120.                     string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); 
    121.                     i += 2; 
    122.                 } 
    123.                 else { 
    124.                     c2 = utftext.charCodeAt(i+1); 
    125.                     c3 = utftext.charCodeAt(i+2); 
    126.                     string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); 
    127.                     i += 3; 
    128.                 } 
    129.  
    130.             } 
    131.  
    132.             return string; 
    133.         } 
    134.  
    135.     } 


    5.hmac.js代码
     

    1. import Crypto from '@/libs/crypto/crypto.js'
    2. /*! 
    3.  * Crypto-JS v1.1.0 
    4.  * http://code.google.com/p/crypto-js/ 
    5.  * Copyright (c) 2009, Jeff Mott. All rights reserved. 
    6.  * http://code.google.com/p/crypto-js/wiki/License 
    7.  */ 
    8. (function(){ 
    9.  
    10. // Shortcut 
    11. var util = Crypto.util; 
    12.  
    13. Crypto.HMAC = function (hasher, message, key, options) { 
    14.  
    15.     // Allow arbitrary length keys 
    16.     key = key.length > hasher._blocksize * 4 ? 
    17.           hasher(key, { asBytes: true }) : 
    18.           util.stringToBytes(key); 
    19.  
    20.     // XOR keys with pad constants 
    21.     var okey = key, 
    22.         ikey = key.slice(0); 
    23.     for (var i = 0; i < hasher._blocksize * 4; i++) { 
    24.         okey[i] ^= 0x5C; 
    25.         ikey[i] ^= 0x36; 
    26.     } 
    27.  
    28.     var hmacbytes = hasher(util.bytesToString(okey) + 
    29.                            hasher(util.bytesToString(ikey) + message, { asString: true }), 
    30.                            { asBytes: true }); 
    31.     return options && options.asBytes ? hmacbytes : 
    32.            options && options.asString ? util.bytesToString(hmacbytes) : 
    33.            util.bytesToHex(hmacbytes); 
    34.  
    35. }; 
    36.  
    37. })(); 

    6.sha1.js代码

    1. import Crypto from '@/libs/crypto/crypto.js'
    2. /*! 
    3.  * Crypto-JS v1.1.0 
    4.  * http://code.google.com/p/crypto-js/ 
    5.  * Copyright (c) 2009, Jeff Mott. All rights reserved. 
    6.  * http://code.google.com/p/crypto-js/wiki/License 
    7.  */ 
    8. (function(){ 
    9.  
    10. // Shortcut 
    11. var util = Crypto.util; 
    12.  
    13. // Public API 
    14. var SHA1 = Crypto.SHA1 = function (message, options) { 
    15.     var digestbytes = util.wordsToBytes(SHA1._sha1(message)); 
    16.     return options && options.asBytes ? digestbytes : 
    17.            options && options.asString ? util.bytesToString(digestbytes) : 
    18.            util.bytesToHex(digestbytes); 
    19. }; 
    20.  
    21. // The core 
    22. SHA1._sha1 = function (message) { 
    23.  
    24.     var m  = util.stringToWords(message), 
    25.         l  = message.length * 8, 
    26.         w  =  [], 
    27.         H0 =  1732584193, 
    28.         H1 = -271733879, 
    29.         H2 = -1732584194, 
    30.         H3 =  271733878, 
    31.         H4 = -1009589776; 
    32.  
    33.     // Padding 
    34.     m[l >> 5] |= 0x80 << (24 - l % 32); 
    35.     m[((l + 64 >>> 9) << 4) + 15] = l; 
    36.  
    37.     for (var i = 0; i < m.length; i += 16) { 
    38.  
    39.         var a = H0, 
    40.             b = H1, 
    41.             c = H2, 
    42.             d = H3, 
    43.             e = H4; 
    44.  
    45.         for (var j = 0; j < 80; j++) { 
    46.  
    47.             if (j < 16) w[j] = m[i + j]; 
    48.             else { 
    49.                 var n = w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16]; 
    50.                 w[j] = (n << 1) | (n >>> 31); 
    51.             } 
    52.  
    53.             var t = ((H0 << 5) | (H0 >>> 27)) + H4 + (w[j] >>> 0) + ( 
    54.                      j < 20 ? (H1 & H2 | ~H1 & H3) + 1518500249 : 
    55.                      j < 40 ? (H1 ^ H2 ^ H3) + 1859775393 : 
    56.                      j < 60 ? (H1 & H2 | H1 & H3 | H2 & H3) - 1894007588 : 
    57.                               (H1 ^ H2 ^ H3) - 899497514); 
    58.  
    59.             H4 =  H3; 
    60.             H3 =  H2; 
    61.             H2 = (H1 << 30) | (H1 >>> 2); 
    62.             H1 =  H0; 
    63.             H0 =  t; 
    64.  
    65.         } 
    66.  
    67.         H0 += a; 
    68.         H1 += b; 
    69.         H2 += c; 
    70.         H3 += d; 
    71.         H4 += e; 
    72.  
    73.     } 
    74.  
    75.     return [H0, H1, H2, H3, H4]; 
    76.  
    77. }; 
    78.  
    79. // Package private blocksize 
    80. SHA1._blocksize = 16; 
    81.  
    82. })(); 

     

    转载请注明(B5教程网)原文链接:https://b5.mxunkeji.com/content-146-6346-1.html
    相关热词搜索: uniapp uniapp教程