almost-utils.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. /**
  2. * 存储 localStorage 数据
  3. * @param {String} name - 缓存数据的标识
  4. * @param {any} content - 缓存的数据内容
  5. */
  6. export const setStore = (name, content) => {
  7. if (!name) return
  8. if (typeof content !== 'string') {
  9. content = JSON.stringify(content)
  10. }
  11. uni.setStorageSync(name, content)
  12. }
  13. /**
  14. * 获取 localStorage 数据
  15. * @param {String} name - 缓存数据的标识
  16. */
  17. export const getStore = (name) => {
  18. if (!name) return
  19. return uni.getStorageSync(name)
  20. }
  21. /**
  22. * 清除 localStorage 数据
  23. * @param {String} name - 缓存数据的标识
  24. */
  25. export const clearStore = (name) => {
  26. if (name) {
  27. uni.removeStorageSync(name)
  28. } else {
  29. console.log('清理本地全部缓存')
  30. uni.clearStorageSync()
  31. }
  32. }
  33. /**
  34. * 绘制圆形
  35. * @param {String} ctx - 图片网络地址
  36. * @param {String} img - 图片地址
  37. * @param {String} x - x 轴偏移量
  38. * @param {String} y - y 轴偏移量
  39. * @param {String} w - 宽
  40. * @param {String} h - 高
  41. */
  42. export const circleImg = (ctx, img, x, y, w, h) => {
  43. let r = Math.floor(w/2)
  44. let cx = x + r
  45. let cy = y + r
  46. ctx.save()
  47. ctx.beginPath()
  48. ctx.arc(cx, cy, r, 0, Math.PI * 2)
  49. ctx.fill()
  50. ctx.clip()
  51. ctx.drawImage(img, x, y, w, h)
  52. ctx.restore()
  53. }
  54. /**
  55. * 计算文本的长度
  56. * @param {String} text - 文本内容
  57. */
  58. export const clacTextLen = (text) => {
  59. if (!text) return { byteLen: 0, realLen: 0 }
  60. text += ''
  61. let clacLen = 0
  62. for (let i = 0; i < text.length; i++) {
  63. if ((text.charCodeAt(i) < 0) || (text.charCodeAt(i) > 255)) {
  64. clacLen += 2
  65. } else {
  66. clacLen += 1
  67. }
  68. }
  69. // console.log(`当前文本 ${text} 的长度为 ${clacLen / 2}`)
  70. return {
  71. byteLen: clacLen,
  72. realLen: clacLen / 2
  73. }
  74. }
  75. /**
  76. * 下载文件,并返回临时路径
  77. * @return {String} 临时路径
  78. * @param {String} fileUrl - 网络地址
  79. */
  80. export const downloadFile = (fileUrl) => {
  81. return new Promise((resolve) => {
  82. uni.downloadFile({
  83. url: fileUrl,
  84. success: (res) => {
  85. resolve({
  86. ok: true,
  87. data: res.errMsg,
  88. tempFilePath: res.tempFilePath
  89. })
  90. },
  91. fail: (err) => {
  92. resolve({
  93. ok: false,
  94. data: err.errMsg,
  95. msg: '图片下载失败'
  96. })
  97. }
  98. })
  99. })
  100. }
  101. /**
  102. * 清理应用已缓存的文件
  103. */
  104. export const clearCacheFile = () => {
  105. // #ifndef H5
  106. uni.getSavedFileList({
  107. success: (res) => {
  108. let fileList = res.fileList
  109. if (fileList.length) {
  110. for (let i = 0; i < fileList.length; i++) {
  111. uni.removeSavedFile({
  112. filePath: fileList[i].filePath,
  113. complete: () => {
  114. console.log('清除缓存已完成')
  115. }
  116. })
  117. }
  118. }
  119. },
  120. fail: (err) => {
  121. console.log('getSavedFileList Fail')
  122. }
  123. })
  124. // #endif
  125. }
  126. // 图像转换工具,可用于图像和base64的转换
  127. // https://ext.dcloud.net.cn/plugin?id=123
  128. const getLocalFilePath = (path) => {
  129. if (
  130. path.indexOf('_www') === 0 ||
  131. path.indexOf('_doc') === 0 ||
  132. path.indexOf('_documents') === 0 ||
  133. path.indexOf('_downloads') === 0
  134. ) return path
  135. if (path.indexOf('/storage/emulated/0/') === 0) return path
  136. if (path.indexOf('/storage/sdcard0/') === 0) return path
  137. if (path.indexOf('/var/mobile/') === 0) return path
  138. if (path.indexOf('file://') === 0) return path
  139. if (path.indexOf('/') === 0) {
  140. // ios 无法获取本地路径
  141. let localFilePath = plus.os.name === 'iOS' ? path : plus.io.convertLocalFileSystemURL(path)
  142. if (localFilePath !== path) {
  143. return localFilePath
  144. } else {
  145. path = path.substring(1)
  146. }
  147. }
  148. return '_www/' + path
  149. }
  150. export const pathToBase64 = (path) => {
  151. return new Promise((resolve, reject) => {
  152. if (typeof window === 'object' && 'document' in window) {
  153. if (typeof FileReader === 'function') {
  154. let xhr = new XMLHttpRequest()
  155. xhr.open('GET', path, true)
  156. xhr.responseType = 'blob'
  157. xhr.onload = function() {
  158. if (this.status === 200) {
  159. let fileReader = new FileReader()
  160. fileReader.onload = function(e) {
  161. resolve(e.target.result)
  162. }
  163. fileReader.onerror = reject
  164. fileReader.readAsDataURL(this.response)
  165. }
  166. }
  167. xhr.onerror = reject
  168. xhr.send()
  169. return
  170. }
  171. let canvas = document.createElement('canvas')
  172. let c2x = canvas.getContext('2d')
  173. let img = new Image
  174. img.onload = function() {
  175. canvas.width = img.width
  176. canvas.height = img.height
  177. c2x.drawImage(img, 0, 0)
  178. resolve(canvas.toDataURL())
  179. canvas.height = canvas.width = 0
  180. }
  181. img.onerror = reject
  182. img.src = path
  183. return
  184. }
  185. if (typeof plus === 'object') {
  186. let tempPath = getLocalFilePath(path)
  187. plus.io.resolveLocalFileSystemURL(tempPath, (entry) => {
  188. entry.file((file) => {
  189. let fileReader = new plus.io.FileReader()
  190. fileReader.onload = function(data) {
  191. resolve(data.target.result)
  192. }
  193. fileReader.onerror = function(error) {
  194. console.log(error)
  195. reject(error)
  196. }
  197. fileReader.readAsDataURL(file)
  198. }, (error) => {
  199. reject(error)
  200. })
  201. }, (error) => {
  202. reject(error)
  203. })
  204. return
  205. }
  206. if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
  207. wx.getFileSystemManager().readFile({
  208. filePath: path,
  209. encoding: 'base64',
  210. success: (res) => {
  211. resolve('data:image/png;base64,' + res.data)
  212. },
  213. fail: (error) => {
  214. reject(error)
  215. }
  216. })
  217. return
  218. }
  219. reject(new Error('not support'))
  220. })
  221. }
  222. export const base64ToPath = (base64) => {
  223. return new Promise((resolve, reject) => {
  224. if (typeof window === 'object' && 'document' in window) {
  225. base64 = base64.split(',')
  226. let type = base64[0].match(/:(.*?);/)[1]
  227. let str = atob(base64[1])
  228. let n = str.length
  229. let array = new Uint8Array(n)
  230. while (n--) {
  231. array[n] = str.charCodeAt(n)
  232. }
  233. return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], {
  234. type: type
  235. })))
  236. }
  237. let extName = base64.match(/data\:\S+\/(\S+);/)
  238. if (extName) {
  239. extName = extName[1]
  240. } else {
  241. reject(new Error('base64 error'))
  242. }
  243. let fileName = Date.now() + '.' + extName
  244. if (typeof plus === 'object') {
  245. let bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
  246. bitmap.loadBase64Data(base64, () => {
  247. let filePath = '_doc/uniapp_temp/' + fileName
  248. bitmap.save(filePath, {}, () => {
  249. bitmap.clear()
  250. resolve(filePath)
  251. }, (error) => {
  252. bitmap.clear()
  253. reject(error)
  254. })
  255. }, (error) => {
  256. bitmap.clear()
  257. reject(error)
  258. })
  259. return
  260. }
  261. if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
  262. let filePath = wx.env.USER_DATA_PATH + '/' + fileName
  263. wx.getFileSystemManager().writeFile({
  264. filePath: filePath,
  265. data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
  266. encoding: 'base64',
  267. success: () => {
  268. resolve(filePath)
  269. },
  270. fail: (error) => {
  271. reject(error)
  272. }
  273. })
  274. return
  275. }
  276. reject(new Error('not support'))
  277. })
  278. }