Multipart.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import Plugin from './Plugin'
  2. export default class Multipart extends Plugin {
  3. constructor(core, opts) {
  4. super(core, opts)
  5. this.type = 'uploader'
  6. if (!this.opts.fieldName === undefined) {
  7. this.opts.fieldName = 'files[]'
  8. }
  9. if (this.opts.bundle === undefined) {
  10. this.opts.bundle = true
  11. }
  12. }
  13. run(results) {
  14. console.log({
  15. class : 'Multipart',
  16. method : 'run',
  17. results: results
  18. })
  19. const files = this.extractFiles(results)
  20. this.setProgress(0)
  21. var uploaders = []
  22. if (this.opts.bundle) {
  23. uploaders.push(this.upload(files, 0, files.length))
  24. } else {
  25. for (let i in files) {
  26. uploaders.push(this.upload(files, i, files.length))
  27. }
  28. }
  29. return Promise.all(uploaders)
  30. }
  31. upload(files, current, total) {
  32. var formPost = new FormData()
  33. // turn file into an array so we can use bundle
  34. if (!this.opts.bundle) {
  35. files = [files[current]]
  36. }
  37. for (let i in files) {
  38. formPost.append(this.opts.fieldName, files[i])
  39. }
  40. var xhr = new XMLHttpRequest()
  41. xhr.open('POST', this.opts.endpoint, true)
  42. xhr.addEventListener('progress', (e) => {
  43. var percentage = (e.loaded / e.total * 100).toFixed(2)
  44. this.setProgress(percentage, current, total)
  45. })
  46. xhr.addEventListener('load', () => {
  47. var upload = {}
  48. if (this.opts.bundle) {
  49. upload = {files: files}
  50. } else {
  51. upload = {file: files[current]}
  52. }
  53. return Promise.resolve(upload)
  54. })
  55. xhr.addEventListener('error', () => {
  56. return Promise.reject('fucking error!')
  57. })
  58. xhr.send(formPost)
  59. }
  60. }