前端阿里云OSS直传

  1. List item

一、web端

引入oss

npm install ali-oss

生成oss实例

//从后端获取STS访问凭证
const credentialsRes = await getOssCredentials();
const {
    accessKeyId,
    accessKeySecret,
    expiration,
    securityToken,
    regionId,
    bucketName,
} = credentialsRes.data;
const expiration = expiration;
// 具体配置详情 https://github.com/ali-sdk/ali-oss?tab=readme-ov-file#ossoptions
const oss = new OSS({
    region: `oss-${regionId}`, //以华东1(杭州)为例,Region填写为oss-cn-hangzhou
    accessKeyId,// 您在阿里云控制台网站上创建的访问密钥
    accessKeySecret, // 您创建的访问密钥
    stsToken: securityToken, // 临时授权使用,详情见https://www.alibabacloud.com/help/zh/oss/developer-reference/upload-objects-using-a-signed-url-generated-with-oss-sdk-for-node-js
    endpoint: endpoint, // oss 地域,优先级高于region。根据不同需求,可以设置为外网域名、内网域名、加速域名等,详情请见https://www.alibabacloud.com/help/zh/oss/user-guide/regions-and-endpoints
    Expiration: expiration,
    secure: true, // 指示 OSS 客户端使用 HTTPS(secure:true)或 HTTP(secure:false)协议
    bucket: bucketName, // 您要访问的默认存储桶如果您没有任何存储桶,请先putBucket()创建一个
    // 2025年09月01日后必须切换到V4签名
    authorizationV4: true, // 使用 V4 签名。默认为 false
    internal:false, // 是否通过阿里云内网访问OSS,默认是false。如果你的服务器也运行在阿里云上,可以设置一下true
    //以下配置针对下图警告
    refreshSTSToken: ()=>{}, // 启用自动刷新 STS 令牌
    refreshSTSTokenInterval: 300000, // 刷新STSToken间隔的使用时间(毫秒),它应该小于sts info的过期间隔,默认为300000毫秒(5分钟)
    timeout:60, // 所有操作的实例级别超时,默认值为60s
    cname:false, // 默认为 false,使用自定义域名访问 oss。如果为 true,则可以endpoint用自定义域名填写字段
    isRequestPay:false, // 默认false,bucket的请求支付功能是否开启,如果是true,会发送headers'x-oss-request-payer': 'requester'到oss服务器,具体可以查看https://help.aliyun.com/zh/oss/user-guide/enable-pay-by-requester-1
    useFetch:false, // 默认为 false,仅在浏览器中有效,如果为 true,则表示使用 fetch模式上传对象,否则XMLHttpRequest
    enableProxy:false, // 启用代理请求,默认为 false。注意:启用代理请求时,请确保已安装 proxy-agent。[proxy] {String | Object},代理uri或选项,默认为null
    retryMax:3, // 用于在请求错误为网络错误或超时时自动重试发送请求的次数。注意:不支持putwith stream、putStream、appendwith stream,因为流只能被消费一次。
    maxSockets:maxSockets, //  每个主机允许的最大套接字数量。默认值为无穷大
});

// 基本用法
const OSS = require('ali-oss');
const store = new OSS({
  accessKeyId: 'your access key',
  accessKeySecret: 'your access secret',
  bucket: 'your bucket name',
  region: 'oss-cn-hangzhou'
});
  1. 基本用法
const OSS = require('ali-oss');

const store = new OSS({
  accessKeyId: 'your access key',
  accessKeySecret: 'your access secret',
  bucket: 'your bucket name',
  region: 'oss-cn-hangzhou'
});
  1. 使用加速端点
  • 全球加速端点:oss-accelerate.aliyuncs.com
  • 中国大陆以外区域加速端点:oss-accelerate-overseas.aliyuncs.com
const OSS = require('ali-oss');

const store = new OSS({
  accessKeyId: 'your access key',
  accessKeySecret: 'your access secret',
  bucket: 'your bucket name',
  endpoint: 'oss-accelerate.aliyuncs.com'
});
  1. 使用 STS 并刷新 STSToken
const OSS = require('ali-oss');

const store = new OSS({
  accessKeyId: 'your STS key',
  accessKeySecret: 'your STS secret',
  stsToken: 'your STS token',
  refreshSTSToken: async () => { // 刷新临时访问凭证的回调,在上传大文件的时候会用到
    const info = await fetch('you sts server');
    return {
      accessKeyId: info.accessKeyId,
      accessKeySecret: info.accessKeySecret,
      stsToken: info.stsToken
    };
  },
  refreshSTSTokenInterval: 300000
});

上传文件

oss.put(fileName, fileContent, {
  success: (res) => {
    console.log('文件上传成功',res.name);
  },
  error: (err) => {
    console.error('文件上传失败:', err);
  }
});
  • fileName:上传到阿里云的地址;例如:test/admin.jpg
  • fileContent:文件主体,二进制文件

下载文件

oss.get(fileName, function (err, content) {
  if (err) {
    console.error('文件下载失败:', err);
  } else {
    fs.writeFile(downloadFileName, content, function (err) {
      if (err) {
        console.error('保存文件失败:', err);
      } else {
        console.log('文件下载并保存成功');
      }
    });
  }
});
//示例
export async function downLoadOssFile(objectKey, fileName) {
  let downloadLoadingInstance;
  try {
    downloadLoadingInstance = ElLoading.service({
      text: "正在下载数据,请稍候",
      background: "rgba(0, 0, 0, 0.7)",
    });
    const result = await oss.get(objectKey);
    const fileContent = result.content;
    const blob = new Blob([fileContent]);
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    const newFileName = fileName + "." + getFileExtension(objectKey);
    link.download = newFileName;
    link.click();
    URL.revokeObjectURL(link.href);
    downloadLoadingInstance.close();
  } catch (err) {
    console.error("下载文件失败:", err);
    ElMessage.error("下载文件出现错误,请联系管理员!");
    downloadLoadingInstance.close();
  }
}
// 获取文件后缀名
export function getFileExtension(fileName = "") {
  return fileName.split(".").pop().toLowerCase();
}

oss.signatureUrl(fileName) //获取当前文件的访问链接,通过http直接下载

批量下载

import JSZip from "jszip";
import { saveAs } from "file-saver";

//oss批量下载
export async function listFiles(files,fileName) {
  let downloadLoadingInstance;
  try {
    downloadLoadingInstance = ElLoading.service({
      text: "正在下载数据,请稍候",
      background: "rgba(0, 0, 0, 0.7)",
    });
    const zip = new JSZip();
    // let files = [
    //   {
    //     name: '照片.jpg',
    //     fileKey:"document/1689680603799buluofen.jpg"
    //   },
    // ];
    // 批量下载文件
    await Promise.all(files.map((file) => downloadFile(file)));
    const zipBlob = await zip.generateAsync({ type: "blob" });
    const zipName=`${fileName}${Number(new Date())}.zip`
    saveAs(zipBlob, zipName);
    downloadLoadingInstance.close();
    async function downloadFile(file) {
      const result = await oss.get(file.fileKey);
      const content = result.content;
      zip.file(file.name, content);
    }
  } catch (error) {
    console.error("下载文件失败:", error);
    ElMessage.error("下载文件出现错误,请联系管理员!");
    downloadLoadingInstance.close();
  }
}

二、移动端

说明:移动端不支持dom操作,引入SDK会报错,需要前端手动加密和拼接访问路径

oss.js文件

import store from "@/store";
import crypto2 from "@/utils/crypto/crypto.js";
class oss_util {
  constructor(accessKeyId, accessKeySecret, host, stsToken, dir, signature, policyBase64, expireEndTime, bucketName,expiration) {
    this.accessKeyId = accessKeyId;
    this.accessKeySecret = accessKeySecret;
    this.host = host;
    this.stsToken = stsToken;
    this.dir = dir;
    this.signature = signature;
    this.policyBase64 = policyBase64;
    this.expireEndTime = expireEndTime;
    this.expiration = expiration;
    this.bucketName = bucketName;
    return this;
  }

  // function get_signature() {
  //     policyBase64 = Base64.encode(JSON.stringify(policyText))
  //     message = policyBase64
  //     var bytes = Crypto.HMAC(Crypto.SHA1, message, accessKeySecret, { asBytes: true }) ;
  //     this.signature = Crypto.util.bytesToBase64(bytes);
  // }

  random_string(len) {
    len = len || 32;
    var chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
    var maxPos = chars.length;
    var pwd = "";
    for (let i = 0; i < len; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  }

  get_path(filename) {
    return this.dir + "/" + this.random_string(32) + this.get_suffix(filename);
  }

  get_suffix(filename) {
    var pos = filename.lastIndexOf(".");
    var suffix = "";
    if (pos != -1) {
      suffix = filename.substring(pos);
    }
    return suffix;
  }

  get_upload_param(filename) {
    var path = this.get_path(filename);
    var new_multipart_params = {
      key: path,
      policy: this.policyBase64,
      OSSAccessKeyId: this.accessKeyId,
      success_action_status: "200",
      signature: this.signature,
      "x-oss-security-token": this.stsToken,
    };
    return new_multipart_params;
  }

  get_upload_url(fileKey) {
    let strTime = this.expiration.replace(/-/g, "/");
    const EXPIRES = 3600 * 1000 + new Date(strTime).getTime();
    let canonicalString = `GET\n\n\n${EXPIRES}\n/${this.bucketName}/${fileKey}?security-token=${this.stsToken}`;
    let signature = crypto2.createHmac("sha1", this.accessKeySecret);
    let SignatureStr = encodeURIComponent(signature.update(Buffer.from(canonicalString, "utf-8")).digest("base64"));
    return `${this.host}/${fileKey}?OSSAccessKeyId=${
      this.accessKeyId
    }&Expires=${EXPIRES}&Signature=${SignatureStr}&security-token=${encodeURIComponent(this.stsToken)}`;
  }
}

function getOssUtil(dir) {
  const {
    accessKeyId,
    accessKeySecret,
    expiration,
    securityToken: stsToken,
    policyResult,
    bucketName,
    ossEndpoint,
  } = store.state.moduleOss.ossInfo;
  const { signature, polocyBase64: policyBase64, expireEndTime } = policyResult;
  const host = "https://" + bucketName + "." + ossEndpoint;
  return new oss_util(
    accessKeyId,
    accessKeySecret,
    host,
    stsToken,
    dir,
    signature,
    policyBase64,
    expireEndTime,
    bucketName,
    expiration
  );
}

export default function (dir) {
  return new Promise(async (resolve, reject) => {
    try {
      if (store.state.moduleOss.ossInfo) {
        //判断上传时间是否过期
        const ossExpiration = store.state.moduleOss.ossInfo.expiration;
        let strTime = ossExpiration.replace(/-/g, "/");
        if (!ossExpiration || new Date().getTime() > new Date(strTime).getTime()) {
          await store.dispatch("moduleOss/getOssInfo");
        }
        resolve(getOssUtil(dir));
      } else {
        await store.dispatch("moduleOss/getOssInfo");
        resolve(getOssUtil(dir));
      }
    } catch (error) {
      reject(error);
    }
  });
}

store/modules/modulesOss.js

export default {
  namespaced: true,
  state: () => ({
    ossInfo: null,
    expiration: "",
    signature: "",
    policy: "",
    isRequest: false,
  }),
  mutations: {
    //保存数据
    setOssInfo: (state, ossInfo) => (state.ossInfo = ossInfo),
    setIsRequest: (state, isRequest) => (state.isRequest = isRequest),
    setExpiration:(state, expiration) => (state.expiration = expiration),
  },
  actions: {
    //获取oss相关配置数据
    async getOssInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        if (state.isRequest) return;
        commit("setIsRequest", true);
        const params = { openid: "" };
        uni.$u.http
          .get("/resource/alioss/credentials", {
            params,
            custom: { catch: true },
          })
          .then(res => {
            if (res.code === 200) {
              commit("setOssInfo", null);
              commit("setOssInfo", res.data);
              commit("setExpiration", res.data.expiration);
              resolve();
            } else {
              reject(res);
            }
          })
          .catch(err => {
            reject(err);
          }).finally(() => { 
            commit("setIsRequest", false);
          });
      });
    },
    //根据文件名删除oss文件
    async delOssFile({ commit, state }, filePath) {
      return new Promise((resolve, reject) => {
        uni.$u.http
          .get("/resource/alioss/delete", { params: { filePath }, custom: { catch: true } })
          .then(res => {
            resolve(res);
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    //清空重置oss相关信息
    clearOssVuex(context) { 
      context.commit("setIsRequest", false);
    }
  },
  getters: {
    //上传地址
    host: state => {
      const { bucketName, ossEndpoint } = state.ossInfo;
      const host = "https://" + bucketName + "." + ossEndpoint;
      return host;
    },
  },
};

/**
 * {
        "securityToken": "CAISoQJ1q6Ft5B2yfSjIr5DfHYmFjOcW3I+ycn/etzMDQsVkio/Tozz2IHtPfnRpB+Abs/oznGhW6fYelqF+VZJfVEvCYJOCGhnXDVrzDbDasumZsJYF6vT8a2TxZjf/2MjNGZKbKPrWZvaqbX3diyZ32sGUXD6+XlujQ/Lr5Jl8dYZVJFvaCwBLH9BLPABvhdYHPH/KT5aXPwXtn3DbATge2G91gngt7r+kkI/OqEic7jjzwfRHoJ/qcNr2LZsuHu8mA4jpg7MmKfSYgXEOukgSzsos0vwYowWgl8qGHlxc7y+BN+fp6dB1JGd7HPNhQPQZ9aasyKAm5rSLydunlww+NOVUQjnZQ5u73MzHFeWmO9A0b7/nPG7X1dSCJmUkVPrTqrBwGoABhSKirmEevobMXaMW7l0cMokb7iLRBHvN3HUTwF5soYKwuXstY6z5vNtI50mZnaf4K4Iik9hBjUBTaR2/oYTBXqgwh2uIVRfFDy7u49crezQ57ei33URbUC3freX+H5qNKsx0fVkKbZeqThCLxPH3Fqpvw/pGcdCAvpiWsz81e5o=",
        "accessKeySecret": "6DQ4cbHheVPv6ZbDa7ccddAm4LcaPnPQBBkFq9ER2LQd",
        "accessKeyId": "STS.NSjV31a87kMYpYoS3VNJHeJxA",
        "expiration": "2023-07-13 10:34:11",
        "regionId": "cn-chengdu",
        "ossEndpoint": "oss-cn-chengdu.aliyuncs.com",
        "bucketName": "scyzya",
        "policyResult": {
            "polocyBase64": "eyJleHBpcmF0aW9uIjoiMjAyMy0wNy0xM1QwMjozNDoxMi45MzFaIiwiY29uZGl0aW9ucyI6W1siY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjAwXV19",
            "signature": "CvU4EB5+w5ffaBRrjK2kiIGz92I=",
            "expireEndTime": 1689215652931
        }
    }
 */

crypto.js

//crypto.js

var Buffer = require('buffer').Buffer;
var sha = require('./sha');
var md5 = require('./md5');

var algorithms = {
  sha1: sha,
  md5: md5
};

var blocksize = 64;
var zeroBuffer = Buffer.alloc(blocksize);
zeroBuffer.fill(0);

function hmac(fn, key, data) {
  if(!Buffer.isBuffer(key)) key = Buffer.from(key);
  if(!Buffer.isBuffer(data)) data = Buffer.from(data);

  if(key.length > blocksize) {
    key = fn(key)
  } else if(key.length < blocksize) {
    key = Buffer.concat([key, zeroBuffer], blocksize)
  }

  var ipad = Buffer.alloc(blocksize), opad = Buffer.alloc(blocksize);
  for(var i = 0; i < blocksize; i++) {
    ipad[i] = key[i] ^ 0x36
    opad[i] = key[i] ^ 0x5C
  }

  var hash = fn(Buffer.concat([ipad, data]))
  return fn(Buffer.concat([opad, hash]))
}

function hash(alg, key) {
  alg = alg || 'sha1';
  var fn = algorithms[alg];
  var bufs = [];
  var length = 0;
  if(!fn) error('algorithm:', alg, 'is not yet supported');
  return {
    update: function (data) {
      if(!Buffer.isBuffer(data)) data = Buffer.from(data);

      bufs.push(data);
      length += data.length;
      return this
    },
    digest: function (enc) {
      var buf = Buffer.concat(bufs);
      var r = key ? hmac(fn, key, buf) : fn(buf);
      bufs = null;
      return enc ? r.toString(enc) : r
    }
  }
}

function error () {
  var m = [].slice.call(arguments).join(' ')
  throw new Error([
    m,
    'we accept pull requests',
    'http://github.com/dominictarr/crypto-browserify'
  ].join('\n'))
}

exports.createHash = function (alg) { return hash(alg) };
exports.createHmac = function (alg, key) { return hash(alg, key) };

exports.createCredentials = () => {
  error('sorry,createCredentials is not implemented yet');
};
exports.createCipher = () => {
  error('sorry,createCipher is not implemented yet');
};
exports.createCipheriv = () => {
  error('sorry,createCipheriv is not implemented yet');
};
exports.createDecipher = () => {
  error('sorry,createDecipher is not implemented yet');
};
exports.createDecipheriv = () => {
  error('sorry,createDecipheriv is not implemented yet');
};
exports.createSign = () => {
  error('sorry,createSign is not implemented yet');
};
exports.createVerify = () => {
  error('sorry,createVerify is not implemented yet');
};
exports.createDiffieHellman = () => {
  error('sorry,createDiffieHellman is not implemented yet');
};
exports.pbkdf2 = () => {
  error('sorry,pbkdf2 is not implemented yet');
};

//helpers.js

//helpers.js
var Buffer = require('buffer').Buffer;
var intSize = 4;
var zeroBuffer = Buffer.alloc(intSize); zeroBuffer.fill(0);
var chrsz = 8;

function toArray(buf, bigEndian) {
  if ((buf.length % intSize) !== 0) {
    var len = buf.length + (intSize - (buf.length % intSize));
    buf = Buffer.concat([buf, zeroBuffer], len);
  }

  var arr = [];
  var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE;
  for (var i = 0; i < buf.length; i += intSize) {
    arr.push(fn.call(buf, i));
  }
  return arr;
}

function toBuffer(arr, size, bigEndian) {
  var buf = Buffer.alloc(size);
  var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE;
  for (var i = 0; i < arr.length; i++) {
    fn.call(buf, arr[i], i * 4, true);
  }
  return buf;
}

function hash(buf, fn, hashSize, bigEndian) {
  if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf);
  var arr = fn(toArray(buf, bigEndian), buf.length * chrsz);
  return toBuffer(arr, hashSize, bigEndian);
}

module.exports = { hash: hash };

//md5.js

//md5.js
/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

var helpers = require('./helpers');

/*
 * Perform a simple self-test to see if the VM is working
 */
function md5_vm_test()
{
  return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}

/*
 * Calculate the MD5 of an array of little-endian words, and a bit length
 */
function core_md5(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);

}

/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

module.exports = function md5(buf) {
  return helpers.hash(buf, core_md5, 16);
};

//sha.js

//sha.js
/*
 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
 * in FIPS PUB 180-1
 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for details.
 */

var helpers = require('./helpers');

/*
 * Calculate the SHA-1 of an array of big-endian words, and a bit length
 */
function core_sha1(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << (24 - len % 32);
  x[((len + 64 >> 9) << 4) + 15] = len;

  var w = Array(80);
  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;
  var e = -1009589776;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;
    var olde = e;

    for(var j = 0; j < 80; j++)
    {
      if(j < 16) w[j] = x[i + j];
      else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
      var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
        safe_add(safe_add(e, w[j]), sha1_kt(j)));
      e = d;
      d = c;
      c = rol(b, 30);
      b = a;
      a = t;
    }

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
    e = safe_add(e, olde);
  }
  return Array(a, b, c, d, e);

}

/*
 * Perform the appropriate triplet combination function for the current
 * iteration
 */
function sha1_ft(t, b, c, d)
{
  if(t < 20) return (b & c) | ((~b) & d);
  if(t < 40) return b ^ c ^ d;
  if(t < 60) return (b & c) | (b & d) | (c & d);
  return b ^ c ^ d;
}

/*
 * Determine the appropriate additive constant for the current iteration
 */
function sha1_kt(t)
{
  return (t < 20) ?  1518500249 : (t < 40) ?  1859775393 :
    (t < 60) ? -1894007588 : -899497514;
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

module.exports = function sha1(buf) {
  return helpers.hash(buf, core_sha1, 20, true);
};

使用oss上传

//oss
import useOss from '@/utils/oss.js'
uploadFilePromise(file) {
      //  #ifdef  APP-PLUS
      let pos = file.url.lastIndexOf("/");
      if (pos != -1) {
        file.name = file.url.substring(pos + 1);
      }
      //  #endif
      return new Promise(async (resolve, reject) => {
        try {
          const oss = await useOss(this.dir);//获取oss实例
          const new_multipart_params = oss.get_upload_param(file.name);
          let a = uni.uploadFile({
            url: oss.host,
            filePath: file.url,
            name: "file",//必须选择file
            formData: new_multipart_params,
            success: res => {
              // console.log('uni.uploadFile success():', res)
              if (res.statusCode === 204 || res.statusCode === 200) {
                // 上传成功
                const { key } = new_multipart_params;
                const ossFileUrl = oss.get_upload_url(key);
                resolve({ url: ossFileUrl, key, status: "success" });
              } else {
                // console.log('-------------uploaded failed')
                uni.showToast({
                  title: "上传失败",
                  duration: 2000,
                  icon: "error",
                });
                resolve({ status: "failed" });
              }
            },
            fail(err) {
              reject();
              // console.log('-------------uploaded failed', err)
            },
          });
        } catch (error) {
          console.log('-------------uploaded failed', error)
          resolve({ status: "failed" });
        }
      });
    },

下载文件

import useOss from '@/utils/oss.js'
const oss = await useOss()
const ossFileURL = oss.get_upload_url(ossUrl)
  //移动端下载文件
  function saveFileToApp(url) {
    var dtask = plus.downloader.createDownload(url, {}, function (d, status) {
      if (status == 200) {
        uni.showToast({
          title: `文件保存路径` + d.filename,
          position: "bottom",
          duration: 2000,
        });
        uni.showModal({
          title: "下载成功",
          content: "是否需要打开该文件?",
          success: function (res) {
            if (res.confirm) {
              uni.openDocument({
                filePath: d.filename,
                showMenu: true,
                success: function (res) {
                  console.log("打开文档成功");
                },
              });
              // plus.runtime.openFile(plus.io.convertLocalFileSystemURL(d.filename), {}, function (success) {
              // 	console.log('打开成功')
              // }, function (error) {
              // 	console.log('打开失败')
              // })
            }
          },
        });
      } else {
        uni.showToast({
          title: "下载失败",
          position: "bottom",
          duration: 1500,
        });
        plus.downloader.clear(); //清除下载任务
      }
    });
    try {
      dtask.start();
      var prg = 0;
      var showLoading = plus.nativeUI.showWaiting("正在下载");
      dtask.addEventListener("statechanged", function (task, status) {
        switch (task.state) {
          case 1:
            showLoading.setTitle("正在下载");
            break;
          case 2:
            showLoading.setTitle("已连接到服务器");
            break;
          case 3:
            prg = parseInt(
              (parseFloat(task.downloadedSize) / parseFloat(task.totalSize)) *
                100
            );
            showLoading.setTitle("  正在下载" + prg + "%  ");
            break;
          case 4:
            plus.nativeUI.closeWaiting();
            //下载完成
            break;
        }
      });
    } catch (err) {
      plus.nativeUI.closeWaiting();
      uni.showToast({
        title: "更新失败",
        mask: false,
        duration: 1500,
      });
    }
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值