aboutsummaryrefslogtreecommitdiffstats
path: root/actiontext/app/javascript/actiontext/attachment_upload.js
diff options
context:
space:
mode:
authorGeorge Claghorn <george@basecamp.com>2019-01-04 19:43:11 -0500
committerGeorge Claghorn <george@basecamp.com>2019-01-04 22:22:49 -0500
commit0decd2ddc4a94cf522fc8ea8e6c73b9deedfdd93 (patch)
tree91b8ddcf86b15356cd8d3dee235bf53a1778572b /actiontext/app/javascript/actiontext/attachment_upload.js
parent8a23a0e8c20c0cccf0073906d7dd7f809bfa836d (diff)
parentcfe4674d3637c746cdb3c2b5131e2de498775529 (diff)
downloadrails-0decd2ddc4a94cf522fc8ea8e6c73b9deedfdd93.tar.gz
rails-0decd2ddc4a94cf522fc8ea8e6c73b9deedfdd93.tar.bz2
rails-0decd2ddc4a94cf522fc8ea8e6c73b9deedfdd93.zip
Import Action Text
Diffstat (limited to 'actiontext/app/javascript/actiontext/attachment_upload.js')
-rw-r--r--actiontext/app/javascript/actiontext/attachment_upload.js45
1 files changed, 45 insertions, 0 deletions
diff --git a/actiontext/app/javascript/actiontext/attachment_upload.js b/actiontext/app/javascript/actiontext/attachment_upload.js
new file mode 100644
index 0000000000..a716f1f589
--- /dev/null
+++ b/actiontext/app/javascript/actiontext/attachment_upload.js
@@ -0,0 +1,45 @@
+import { DirectUpload } from "activestorage"
+
+export class AttachmentUpload {
+ constructor(attachment, element) {
+ this.attachment = attachment
+ this.element = element
+ this.directUpload = new DirectUpload(attachment.file, this.directUploadUrl, 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
+ }
+}