Sha256: 3df46d8b074a09a53c3d47f97dcb97f37d3ab1a380068b9257d800206c37649d

Contents?: true

Size: 1.41 KB

Versions: 5

Compression:

Stored size: 1.41 KB

Contents

import { DirectUpload } from "@rails/activestorage"

export class AttachmentUpload {
  constructor(attachment, element) {
    this.attachment = attachment
    this.element = element
    this.directUpload = new DirectUpload(attachment.file, this.directUploadUrl, this.directUploadToken, this.attachmentName, this)
  }

  start() {
    this.directUpload.create(this.directUploadDidComplete.bind(this))
  }

  directUploadWillStoreFileWithXHR(xhr) {
    xhr.upload.addEventListener("progress", event => {
      const progress = event.loaded / event.total * 100
      this.attachment.setUploadProgress(progress)
    })
  }

  directUploadDidComplete(error, attributes) {
    if (error) {
      throw new Error(`Direct upload failed: ${error}`)
    }

    this.attachment.setAttributes({
      sgid: attributes.attachable_sgid,
      url: this.createBlobUrl(attributes.signed_id, attributes.filename)
    })
  }

  createBlobUrl(signedId, filename) {
    return this.blobUrlTemplate
      .replace(":signed_id", signedId)
      .replace(":filename", encodeURIComponent(filename))
  }

  get directUploadUrl() {
    return this.element.dataset.directUploadUrl
  }

  get blobUrlTemplate() {
    return this.element.dataset.blobUrlTemplate
  }

  get directUploadToken() {
    return this.element.getAttribute("data-direct-upload-token");
  }
  get attachmentName() {
    return this.element.getAttribute("data-direct-upload-attachment-name");
  }
}

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
actiontext-7.0.1 app/javascript/actiontext/attachment_upload.js
actiontext-7.0.0 app/javascript/actiontext/attachment_upload.js
actiontext-7.0.0.rc3 app/javascript/actiontext/attachment_upload.js
actiontext-7.0.0.rc2 app/javascript/actiontext/attachment_upload.js
actiontext-7.0.0.rc1 app/javascript/actiontext/attachment_upload.js