FileInput.js 2.3 KB

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