parse-image-url.js 1.5 KB

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