domGetFiles.mjs

  1. import get from 'lodash-es/get.js'
  2. import each from 'lodash-es/each.js'
  3. import cdbl from './cdbl.mjs'
  4. /**
  5. * 前端回傳Input元素所給予的檔案
  6. *
  7. * Unit Test: {@link https://github.com/yuda-lyu/wsemi/blob/master/test/domGetFiles.test.mjs Github}
  8. * @memberOf wsemi
  9. * @param {Element} ele 輸入Element Input元素
  10. * @param {Number} [sizeMbLimit=1000] 輸入檔案大小上線,單位mb,預設為1000mb(約1g)
  11. * @returns {Array} 回傳檔案陣列
  12. * @example
  13. * need test in browser
  14. *
  15. * let ele = document.querySelector('#id')
  16. * let r = domGetFiles(ele)
  17. *
  18. */
  19. function domGetFiles(ele, sizeMbLimit = 1000) {
  20. //check
  21. sizeMbLimit = cdbl(sizeMbLimit)
  22. if (sizeMbLimit <= 0) {
  23. sizeMbLimit = 1000
  24. }
  25. //files
  26. let errs = {}
  27. let files = []
  28. each(get(ele, 'files', []), function(file, k) {
  29. //sizeB, 單位bytes
  30. let sizeB = file.size
  31. //sizeMb
  32. let sizeMb = sizeB / 1024 / 1024
  33. //check
  34. if (sizeMb > sizeMbLimit) {
  35. //push err
  36. errs[k] = `file size[${sizeMb}]mb > ${sizeMbLimit}mb`
  37. }
  38. //push file
  39. files.push(file)
  40. })
  41. return {
  42. files,
  43. errs,
  44. }
  45. }
  46. export default domGetFiles