AttachFileInputs.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. const { Plugin } = require('@uppy/core')
  2. const toArray = require('@uppy/utils/lib/toArray')
  3. const findDOMElement = require('@uppy/utils/lib/findDOMElement')
  4. /**
  5. * Add files from existing file inputs to Uppy.
  6. */
  7. class AttachFileInputs extends Plugin {
  8. constructor (uppy, opts) {
  9. super(uppy, opts)
  10. this.id = this.opts.id || 'AttachFileInputs'
  11. this.type = 'acquirer'
  12. this.handleChange = this.handleChange.bind(this)
  13. this.inputs = null
  14. }
  15. handleChange (event) {
  16. this.addFiles(event.target)
  17. }
  18. addFiles (input) {
  19. const files = toArray(input.files)
  20. files.forEach((file) => {
  21. try {
  22. this.uppy.addFile({
  23. source: this.id,
  24. name: file.name,
  25. type: file.type,
  26. data: file
  27. })
  28. } catch (err) {
  29. if (!err.isRestriction) {
  30. this.uppy.log(err)
  31. }
  32. }
  33. })
  34. }
  35. install () {
  36. this.el = findDOMElement(this.opts.target)
  37. if (!this.el) {
  38. throw new Error('[AttachFileInputs] Target form does not exist')
  39. }
  40. const { restrictions } = this.uppy.opts
  41. this.inputs = this.el.querySelectorAll('input[type="file"]')
  42. this.inputs.forEach((input) => {
  43. input.addEventListener('change', this.handleChange)
  44. if (!input.hasAttribute('multiple')) {
  45. if (restrictions.maxNumberOfFiles !== 1) {
  46. input.setAttribute('multiple', 'multiple')
  47. } else {
  48. input.removeAttribute('multiple')
  49. }
  50. }
  51. if (!input.hasAttribute('accept') && restrictions.allowedFileTypes) {
  52. input.setAttribute('accept', restrictions.allowedFileTypes.join(','))
  53. }
  54. // Check if this input already contains files (eg. user selected them before Uppy loaded,
  55. // or the page was refreshed and the browser kept files selected)
  56. this.addFiles(input)
  57. })
  58. }
  59. uninstall () {
  60. this.inputs.forEach((input) => {
  61. input.removeEventListener('change', this.handleChange)
  62. })
  63. this.inputs = null
  64. }
  65. }
  66. module.exports = AttachFileInputs