download.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import path from 'path'
  2. var queue = [] // 下载队列 避免重复下载
  3. /**
  4. * 下载文件
  5. * @param {string} url 要下载文件资源地址
  6. * @param {string} [dir] 下载文件保存的路径
  7. * @returns {Promise<string|null>} 下载后的本地路径
  8. */
  9. function download(url, dir) {
  10. return new Promise(resolve => {
  11. if (queue.includes(url)) return
  12. queue.push(url)
  13. const task = plus.downloader.createDownload(
  14. url,
  15. dir ? { filename: filename(url, dir) } : {},
  16. (download, status) => {
  17. queue.splice(queue.indexOf(url), 1)
  18. resolve(status === 200 ? download.filename : null)
  19. }
  20. )
  21. task.start()
  22. })
  23. }
  24. /**
  25. * 生成随机文件名后的路径
  26. * @param {string} url 网络地址
  27. * @param {string} dir 保存的路径
  28. * @returns {string} 随机文件名后的路径
  29. */
  30. function filename(url, dir) {
  31. const CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  32. let random = ''
  33. for (let i = 0; i < 4; i++) {
  34. const index = parseInt(Math.random() * CHARS.length)
  35. random += CHARS[index]
  36. }
  37. dir = dir.replace(/(^\/)|(\/$)/g, '')
  38. const name = Date.now() + random + path.extname(url)
  39. return `_doc/${dir}/${name}`
  40. }
  41. export default download