AttachFileInputs.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 = 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. // Nothing, restriction errors handled in Core
  30. }
  31. })
  32. }
  33. install () {
  34. this.el = findDOMElement(this.opts.target)
  35. if (!this.el) {
  36. throw new Error('[AttachFileInputs] Target form does not exist')
  37. }
  38. const { restrictions } = this.uppy.opts
  39. this.inputs = this.el.querySelectorAll('input[type="file"]')
  40. this.inputs.forEach((input) => {
  41. input.addEventListener('change', this.handleChange)
  42. if (!input.hasAttribute('multiple')) {
  43. if (restrictions.maxNumberOfFiles !== 1) {
  44. input.setAttribute('multiple', 'multiple')
  45. } else {
  46. input.removeAttribute('multiple')
  47. }
  48. }
  49. if (!input.hasAttribute('accept') && restrictions.allowedFileTypes) {
  50. input.setAttribute('accept', restrictions.allowedFileTypes.join(','))
  51. }
  52. // Check if this input already contains files (eg. user selected them before Uppy loaded,
  53. // or the page was refreshed and the browser kept files selected)
  54. this.addFiles(input)
  55. })
  56. }
  57. uninstall () {
  58. this.inputs.forEach((input) => {
  59. input.removeEventListener('change', this.handleChange)
  60. })
  61. this.inputs = null
  62. }
  63. }
  64. module.exports = AttachFileInputs