parse-image-url.uts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. export type ParseImageUrlResult = {
  2. src: string
  3. source: string
  4. }
  5. function parseEditorImage (_blocks: any): UTSJSONObject[] {
  6. const images: UTSJSONObject[] = []
  7. let blocks: UTSJSONObject[]
  8. if (!Array.isArray(_blocks)) {
  9. blocks = [_blocks as UTSJSONObject] as UTSJSONObject[]
  10. } else {
  11. blocks = _blocks as UTSJSONObject[]
  12. }
  13. blocks.forEach((block: UTSJSONObject) => {
  14. const insert = block.getJSON('insert')
  15. const attributes = block.getJSON('attributes')
  16. const custom = attributes!.getString('data-custom')
  17. let parseCustom = custom && custom.split('&') ? custom.split('&').reduce((obj: UTSJSONObject, item: string): UTSJSONObject => {
  18. const kv = item.split('=')
  19. if (kv.length > 1) {
  20. obj[kv[0]] = kv[1]
  21. }
  22. return obj
  23. }, {} as UTSJSONObject) : {}
  24. images.push({
  25. src: insert!.getString('image'),
  26. source: parseCustom.getString('source') != null ? parseCustom.getString('source') : insert!.getString('image')
  27. })
  28. })
  29. return images
  30. }
  31. /**
  32. * 解析媒体库/编辑器中的图片
  33. * @param images 图片地址
  34. * @param type {string} 解析类型 media: 媒体库, editor: 编辑器
  35. * @returns {Promise<{src: *, source: *}[]|{src, source: *}[]>}
  36. */
  37. export async function parseImageUrl (images: any, type: string = "media"): Promise<ParseImageUrlResult[] | null> {
  38. let imagePaths: string[] = []
  39. if (type === "editor") {
  40. imagePaths = parseEditorImage(images).map((item: UTSJSONObject): string => item.getString('source')!)
  41. } else {
  42. if (!Array.isArray(images)) {
  43. imagePaths = [images as string] as string[]
  44. } else {
  45. imagePaths = images
  46. }
  47. }
  48. if (imagePaths.length <= 0) return null
  49. const tcbFiles = imagePaths.filter((item: string): boolean => item.startsWith("cloud://"))
  50. if (tcbFiles.length > 0) {
  51. const res: UniCloudGetTempFileURLResult = await uniCloud.getTempFileURL({
  52. fileList: tcbFiles
  53. })
  54. return imagePaths.map((image: string): ParseImageUrlResult => {
  55. const file = res.fileList.find((item: UniCloudGetTempFileURLResultItem): boolean => item.fileID === image)
  56. return {
  57. src: file ? file.tempFileURL : image,
  58. source: image
  59. } as ParseImageUrlResult
  60. })
  61. } else {
  62. return imagePaths.map((image: string): ParseImageUrlResult => ({
  63. src: image,
  64. source: image
  65. } as ParseImageUrlResult))
  66. }
  67. }