FileInput.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. const Plugin = require('../core/Plugin')
  2. const { toArray } = require('../core/Utils')
  3. const Translator = require('../core/Translator')
  4. const { h } = require('preact')
  5. const hyperx = require('hyperx')
  6. const html = hyperx(h)
  7. module.exports = class FileInput extends Plugin {
  8. constructor (uppy, opts) {
  9. super(uppy, opts)
  10. this.id = this.opts.id || 'FileInput'
  11. this.title = 'File Input'
  12. this.type = 'acquirer'
  13. const defaultLocale = {
  14. strings: {
  15. selectToUpload: 'Select to upload'
  16. }
  17. }
  18. // Default options
  19. const defaultOptions = {
  20. target: '.UppyForm',
  21. getMetaFromForm: true,
  22. replaceTargetContent: true,
  23. multipleFiles: true,
  24. pretty: true,
  25. locale: defaultLocale,
  26. inputName: 'files[]'
  27. }
  28. // Merge default options with the ones set by user
  29. this.opts = Object.assign({}, defaultOptions, opts)
  30. this.locale = Object.assign({}, defaultLocale, this.opts.locale)
  31. this.locale.strings = Object.assign({}, defaultLocale.strings, this.opts.locale.strings)
  32. // i18n
  33. this.translator = new Translator({locale: this.locale})
  34. this.i18n = this.translator.translate.bind(this.translator)
  35. this.render = this.render.bind(this)
  36. }
  37. handleInputChange (ev) {
  38. this.uppy.log('All right, something selected through input...')
  39. const files = toArray(ev.target.files)
  40. files.forEach((file) => {
  41. this.uppy.addFile({
  42. source: this.id,
  43. name: file.name,
  44. type: file.type,
  45. data: file
  46. })
  47. })
  48. }
  49. render (state) {
  50. const hiddenInputStyle = 'width: 0.1px; height: 0.1px; opacity: 0; overflow: hidden; position: absolute; z-index: -1;'
  51. const input = html`<input class="uppy-FileInput-input"
  52. style="${this.opts.pretty ? hiddenInputStyle : ''}"
  53. type="file"
  54. name=${this.opts.inputName}
  55. onchange=${this.handleInputChange.bind(this)}
  56. multiple="${this.opts.multipleFiles ? 'true' : 'false'}"
  57. value="">`
  58. return html`<form class="Uppy uppy-FileInput-form">
  59. ${input}
  60. ${this.opts.pretty
  61. ? html`<button class="uppy-FileInput-btn" type="button" onclick=${() => input.click()}>
  62. ${this.i18n('selectToUpload')}
  63. </button>`
  64. : null
  65. }
  66. </form>`
  67. }
  68. install () {
  69. const target = this.opts.target
  70. if (target) {
  71. this.mount(target, this)
  72. }
  73. }
  74. uninstall () {
  75. this.unmount()
  76. }
  77. }