uniapp上传小程序代码
import crypto from 'crypto-js';
import { Base64 } from 'js-base64/base64.js';
// 计算oss签名。
function computeSignature(accessKeySecret, canonicalString) {return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
}
const getPolicyBase64 = function () {let date = new Date();date.setHours(date.getHours() + '87600');let expiration = date.toISOString();const policyText = {"expiration": expiration, //设置该Policy的失效时间"conditions": [["content-length-range", 0, 1024 * 1024 * 1024 * 5] // 设置上传文件的大小限制, 5G]};const policyBase64 = Base64.encode(JSON.stringify(policyText));return policyBase64;
}/*** 获取oss签名*/
export const getOssAuthorization = (callback) => {request({url: `xxxxx`,method: 'get',}).then((res) => {// 返回参数// {// accessKeyId: "",// accessKeySecret: "",// bucket: '',// bucketName: "", 桶名// callback: null,// dir: "",// endpoint: "https://oss-cn-xxxx.aliyuncs.com",// keyName: "",// osBasicInfo: "",// path: '',// region: "",// response: '',// securityToken: ''// }callback && callback(res.data)})
};
/*** * @param {string} filePath 文件的路径* @param {string} fileSize 文件的大小* @param {string} fileSuffix 文件后后缀* @param {string} fileName 文件夹名* @param {*} param* @returns */
export const ossUploadFile = (filePath, fileSize, fileSuffix = '', fileName) => {return new Promise((resolve, reject) => {if (!filePath) {uni.showModal({ title: '文件错误', content: '请重试', showCancel: false });uni.hideLoading();return false;}getOssAuthorization(async(data) => {// 这里指定上传的文件名const aliyunFileKey = `${data.dir}${fileName}`;// 拼接上传的oss地址let str = 'https://'const aliyunServerURL = data.endpoint.replace(str, `${str}${data.bucketName}.`);// 密钥const accessKeyId = data.accessKeyId;// 超时的时间const policyBase64 = getPolicyBase64();// 临时证书const signature = computeSignature(data.accessKeySecret, policyBase64);uni.uploadFile({url: aliyunServerURL, // 上传的域名filePath: filePath, // 上传的文件name: "file",formData: {key: aliyunFileKey, // 文件名称policy: policyBase64, // 过期时间OSSAccessKeyId: accessKeyId, // 秘钥signature: signature, // 临时证书success_action_status: "200","x-oss-security-token": data.securityToken},success: (res) => {console.log("成功回调", res)if (res.statusCode == 200) {let result = aliyunServerURL + "/" + aliyunFileKeyconsole.log(result, '====文件地址');resolve(result)} else {reject(res)}},fail: (err) => {console.log(err, 'err==上传失败');err.wxaddinfo = aliyunServerURLreject(err)},})})});
}