file.js 1.5 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4
import {
  hasOwn
} from 'uni-shared'

fxy060608's avatar
fxy060608 已提交
5
/**
6 7 8 9 10
 * 暂存的文件对象
 */
const files = {}
/**
 * 从url读取File
fxy060608's avatar
fxy060608 已提交
11
 * @param {string} url
12
 * @param {Promise}
fxy060608's avatar
fxy060608 已提交
13
 */
14 15 16 17
export function urlToFile (url) {
  var file = files[url]
  if (file) {
    return Promise.resolve(file)
fxy060608's avatar
fxy060608 已提交
18
  }
19
  if (/^data:[a-z-]+\/[a-z-]+;base64,/.test(url)) {
20
    return Promise.resolve(base64ToFile(url))
21 22 23 24 25 26 27 28 29 30 31
  }
  return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest()
    xhr.open('GET', url, true)
    xhr.responseType = 'blob'
    xhr.onload = function () {
      resolve(this.response)
    }
    xhr.onerror = reject
    xhr.send()
  })
fxy060608's avatar
fxy060608 已提交
32 33
}
/**
34
 * base64转File
fxy060608's avatar
fxy060608 已提交
35
 * @param {string} base64
36
 * @return {File}
fxy060608's avatar
fxy060608 已提交
37
 */
38
export function base64ToFile (base64) {
fxy060608's avatar
fxy060608 已提交
39 40 41 42 43 44 45 46
  base64 = base64.split(',')
  var type = base64[0].match(/:(.*?);/)[1]
  var str = atob(base64[1])
  var n = str.length
  var array = new Uint8Array(n)
  while (n--) {
    array[n] = str.charCodeAt(n)
  }
47 48
  var filename = `${Date.now()}.${type.split('/')[1]}`
  return new File([array], filename, { type: type })
fxy060608's avatar
fxy060608 已提交
49 50 51
}
/**
 * 从本地file或者blob对象创建url
52
 * @param {Blob|File} file
fxy060608's avatar
fxy060608 已提交
53 54
 * @return {string}
 */
55 56
export function fileToUrl (file) {
  for (const key in files) {
fxy060608's avatar
fxy060608 已提交
57
    if (hasOwn(files, key)) {
58 59 60 61 62 63 64 65 66
      const oldFile = files[key]
      if (oldFile === file) {
        return key
      }
    }
  }
  var url = (window.URL || window.webkitURL).createObjectURL(file)
  files[url] = file
  return url
fxy060608's avatar
fxy060608 已提交
67
}
68 69 70 71 72

export function revokeObjectURL (url) {
  (window.URL || window.webkitURL).revokeObjectURL(url)
  delete files[url]
}