// e : 文件对象,filename:存储文件名,tag:识别当前事件的种类,配合fn使用,imgpath:图片路径,fn:回调函数
exportfunctionuploadImg(e, filename, tag, imgpath, fn) { uni.showLoading({ title: '正在上传...' }); if (e.tempFiles.length == 0) { uni.hideLoading(); uni.showToast({ title:'未找到图片', icon:'none' }) }; // 检测图片大小 let file = e.tempFiles[0]; if (file.size > 15728640) { // 15M uni.showToast({ title: "您上传的图片文件过大,请重新上传!", icon: "none" }); returnfalse } lrz(file, { width: 500, }).then(function(res) { let base64 = res.base64; let blob = convertBase64UrlToBlob(base64); let r = Math.random().toString(16).substr(2); let time = newDate(), y, m, d; y = time.getFullYear(); m = String(time.getMonth() + 1).length === 2 ? (time.getMonth() + 1) : "0" + (time.getMonth() + 1); d = String(time.getDate()).length === 2 ? (time.getDate()) : "0" + time.getDate(); let dfilefold = y + m + d; // 创建时间文件夹 let name; if (imgpath.indexOf(filename) != -1) { let tmps = imgpath.split(filename)[1].split('?')[0]; // 获取时间戳 name = filename + tmps; } else { name = filename + dfilefold + '/' + r; } // 上传图片 client.put(name, blob).then(result => { // 上传成功 ; uni.hideLoading(); // 得到图片在oss中的url地址; let path = result.url; fn(tag, path); }).catch(err => { console.log(err) uni.showToast({ title: "图上传失败,请重试!", icon: "none" }) }); }) }
// 辅助函数 functionconvertBase64UrlToBlob(urlData) { var bytes = window.atob(urlData.split(',')[1]); //去掉url的头,并转换为byte //处理异常,将ascii码小于0的转换为大于0 var ab = newArrayBuffer(bytes.length); var ia = newUint8Array(ab); for (var i = 0; i < bytes.length; i++) { ia[i] = bytes.charCodeAt(i); } returnnewBlob([ab], { type: 'image/png' }); };