UNPKG

ipink-util

Version:

util.js

442 lines (439 loc) 13 kB
import { toast } from './toast.mjs'; function getLocalFilePath(path) { if (path.indexOf("_www") === 0 || path.indexOf("_doc") === 0 || path.indexOf("_documents") === 0 || path.indexOf( "_downloads" ) === 0) { return path; } if (path.indexOf("file://") === 0) { return path; } if (path.indexOf("/storage/emulated/0/") === 0) { return path; } if (path.indexOf("/") === 0) { var localFilePath = plus.io.convertAbsoluteFileSystem(path); if (localFilePath !== path) { return localFilePath; } else { path = path.substr(1); } } return "_www/" + path; } function dataUrlToBase64(base64Str) { var array = base64Str.split(","); return array[array.length - 1]; } var index = 0; function getNewFileId() { return Date.now() + String(index++); } function biggerThan(v1, v2) { var v1Array = v1.split("."); var v2Array = v2.split("."); var update = false; for (var index2 = 0; index2 < v2Array.length; index2++) { var diff = +v1Array[index2] - +v2Array[index2]; if (diff !== 0) { update = diff > 0; break; } } return update; } function chooseImage(params) { let { count = 1, sourceType = 1, fileType = "image", extension, showToast = false } = params || {}; return new Promise(async (resolve) => { extension = extension || ["png", "PNG", "JPG", "jpg", "jpeg"]; if (window && window.AlipayJSBridge) { await AlipayJSBridge.call( "chooseImage", { count, // 如果只需要拍照,可以只传['camera'] sourceType: sourceType == 2 ? ["album"] : sourceType == 3 ? ["camera"] : ["album", "camera"] }, async function(chooseImageRes) { const _apFilePath = chooseImageRes.apFilePaths || chooseImageRes.tempFilePaths; let apFilePath = []; if (typeof _apFilePath === "string") { try { apFilePath = JSON.parse(_apFilePath); } catch (e) { } } apFilePath = apFilePath.length ? apFilePath : chooseImageRes.apFilePathsV2 || []; if (!apFilePath.length) { return resolve([]); } if (fileType == "image") { let fIndex = (chooseImageRes.tempFiles || []).findIndex((item) => { var type = item.type; const checkType = (extension || []).map((item2) => "image/" + item2).find((item2) => item2 == type); if (type && !checkType) { return item; } }); if (fIndex >= 0) { toast("选择的文件格式不正确,请重新选择!"); return resolve([]); } } resolve(apFilePath); } ); } else { if (!uni || !uni.chooseImage) return resolve([]); uni.chooseImage({ count, // #ifdef H5 extension, // #endif sourceType: sourceType == 2 ? ["album"] : sourceType == 3 ? ["camera"] : ["album", "camera"], sizeType: ["compressed"], success: (chooseImageRes) => { let apFilePath = chooseImageRes.tempFilePaths; try { if (typeof apFilePath == "string") apFilePath = JSON.parse(apFilePath); } catch (error) { apFilePath = []; } resolve(apFilePath); }, fail(err) { if (showToast) toast(err && err.errMsg || "上传失败!"); resolve([]); } }); } }); } function getImageInfo(url) { const env = uni || wx; if (!env || !env.getImageInfo) return Promise.resolve({ msg: "当前环境暂不支持!" }); return new Promise((resolve) => { env.getImageInfo({ src: url, success: (res) => { resolve(res); }, fail: (err) => { resolve(err); } }); }); } async function pathToBase64(path, info, width, height) { height = height || 300; return new Promise(async function(resolve, reject) { if (window && window.AlipayJSBridge) { var image = new Image(); image.crossOrigin = "anonymous"; image.src = path; image.onload = await function() { var canvas2 = document.createElement("CANVAS"); var context = canvas2.getContext("2d"); canvas2.height = image.height; canvas2.width = image.width; context.drawImage(image, 0, 0); try { var dataURL = canvas2.toDataURL("image/png"); canvas2 = null; return resolve({ base64: dataURL, file: path }); } catch (e) { canvas2 = null; return resolve({ base64: "", file: path }); } }; return; } if (typeof window === "object" && "document" in window) { if (typeof FileReader === "function") { var xhr = new XMLHttpRequest(); xhr.open("GET", path, true); xhr.responseType = "blob"; xhr.onload = function() { if (this.status === 200) { let fileReader = new FileReader(); fileReader.onload = function(e) { resolve({ base64: e.target.result, file: path }); }; fileReader.onerror = reject; fileReader.readAsDataURL(this.response); } }; xhr.onerror = reject; xhr.send(); return; } var canvas = document.createElement("canvas"); var c2x = canvas.getContext("2d"); var img = new Image(); img.src = path; img.onload = await function() { canvas.width = img.width; canvas.height = img.height; c2x.drawImage(img, 0, 0); resolve({ base64: canvas.toDataURL(), file: path }); canvas.height = canvas.width = 0; }; img.onerror = reject; img.src = path; canvas = null; return; } if (typeof plus === "object") { await plus.io.resolveLocalFileSystemURL(getLocalFilePath(path), function(entry) { entry.file(function(file) { var fileReader = new plus.io.FileReader(); fileReader.onload = function(data) { resolve({ base64: data.target.result, file: path }); }; fileReader.onerror = function(error) { resolve({ base64: "", file: path }); }; fileReader.readAsDataURL(file); }, function(error) { resolve({ base64: "", file: path }); }); }, function(error) { resolve({ base64: "", file: path }); }); return; } if (typeof wx === "object" && wx.canIUse("getFileSystemManager")) { if (wx && wx.getFileSystemManager) { wx.getFileSystemManager().readFile({ filePath: path, encoding: "base64", success: function(res) { resolve({ base64: "data:image/png;base64," + res.data, file: path, info: res }); }, fail: function(error) { resolve({ base64: "", file: path, err: error }); } }); return; } if (my && my.createCanvasContext) { const ctx = my.createCanvasContext("canvas"); if (info && info.width) { info.width > info.height; let ratio = my.getSystemInfoSync().windowWidth / info.width; ratio * info.height; ctx.drawImage( path, 0, 0, info.width, info.height ); } else { ctx.drawImage(path, 0, 0, width || my.getSystemInfoSync().windowWidth, height); } ctx.draw(false, () => { ctx.toDataURL({}).then((dataURL) => { resolve({ base64: dataURL, file: path }); }).catch((err) => { resolve({ base64: "", file: path, err }); }); }); } return; } resolve({ base64: "", file: path }); }); } function base64ToPath(base64) { return new Promise(function(resolve, reject) { if (typeof window === "object" && "document" in window) { const base64Arr = base64.split(","); var type = base64Arr[0].match(/:(.*?);/)[1]; var str = atob(base64Arr[1]); var n = str.length; var array = new Uint8Array(n); while (n--) { array[n] = str.charCodeAt(n); } return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], { type }))); } var _extName = base64.split(",")[0].match(/data\:\S+\/(\S+);/), extName = ""; if (_extName) { extName = _extName[1]; } else { resolve({ msg: "base64 error" }); } var fileName = getNewFileId() + "." + extName; if (typeof plus === "object") { var basePath = "_doc"; var dirPath = "uniapp_temp"; var filePath = basePath + "/" + dirPath + "/" + fileName; if (!biggerThan( plus.os.name === "Android" ? "1.9.9.80627" : "1.9.9.80472", plus.runtime.innerVersion )) { plus.io.resolveLocalFileSystemURL(basePath, function(entry) { entry.getDirectory(dirPath, { create: true, exclusive: false }, function(entry2) { entry2.getFile(fileName, { create: true, exclusive: false }, function(entry3) { entry3.createWriter(function(writer) { writer.onwrite = function() { resolve(filePath); }; writer.onerror = reject; writer.seek(0); writer.writeAsBinary(dataUrlToBase64(base64)); }, reject); }, reject); }, reject); }, reject); return; } var bitmap = new plus.nativeObj.Bitmap(fileName); bitmap.loadBase64Data(base64, function() { bitmap.save(filePath, {}, function() { bitmap.clear(); resolve(filePath); }, function(error) { bitmap.clear(); reject(error); }); }, function(error) { bitmap.clear(); reject(error); }); return; } if (typeof wx === "object" && wx.canIUse("getFileSystemManager")) { var filePath = wx.env.USER_DATA_PATH + "/" + fileName; wx.getFileSystemManager().writeFile({ filePath, data: dataUrlToBase64(base64), encoding: "base64", success: function() { resolve(filePath); }, fail: function(error) { reject(error); } }); return; } reject(new Error("not support")); }); } function chooseVideo(options) { let { sourceType = 1, maxDuration, camera, compressed, showToast = false } = options || {}; if (!uni || !uni.chooseVideo) return Promise.resolve([]); return new Promise((resolve) => { uni.chooseVideo({ sourceType: sourceType == 2 ? ["album"] : sourceType == 3 ? ["camera"] : ["album", "camera"], maxDuration, camera, compressed, success(res) { resolve([res.tempFilePath]); }, fail(err) { resolve([]); if (showToast) toast(err && err.errMsg || "上传失败!"); } }); }); } function chooseOtherFile(options) { let { count = 1, extension, type = "all", sourceType, showToast = false } = options || {}; extension = extension || [".csv", ".xlsx"]; return new Promise((resolve) => { const params = { count, type, sourceType: sourceType == 2 ? ["album"] : sourceType == 3 ? ["camera"] : ["album", "camera"], extension, fail: (err) => { if (showToast) toast(err && err.errMsg || "上传失败!"); resolve([]); } }; if (wx && wx.chooseMessageFile) { wx.chooseMessageFile({ ...params, success(res) { resolve( // @ts-ignore res && res.tempFilePaths || (res && res.tempFiles && res.tempFiles[0] ? [res.tempFiles[0].path] : []) ); } }); return; } if (uni && uni.chooseFile) { uni.chooseFile({ ...params, success: function(res) { resolve(res.tempFilePaths ? typeof res.tempFilePaths == "string" ? [res.tempFilePaths] : res.tempFilePaths : []); } }); return; } toast("请在「APP」内进行操作, 未安装请先前往下载!"); resolve([]); }); } export { base64ToPath, chooseImage, chooseOtherFile, chooseVideo, getImageInfo, getLocalFilePath, pathToBase64 };