1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Extract AttachmentUpload

This commit is contained in:
Javan Makhmali 2018-02-14 14:35:34 -05:00
parent ba71c73836
commit 55e2df15cd
2 changed files with 50 additions and 28 deletions

View file

@ -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
}
}

View file

@ -1,34 +1,11 @@
import * as Trix from "trix"
import { DirectUpload } from "activestorage"
import { AttachmentUpload } from "./attachment_upload"
addEventListener("trix-attachment-add", event => {
const { attachment } = event
if (!attachment.file) return
const { attachment, target } = event
const { directUploadUrl, blobUrlTemplate } = event.target.dataset
const delegate = {
directUploadWillStoreFileWithXHR: (xhr) => {
xhr.upload.addEventListener("progress", event => {
const progress = event.loaded / event.total * 100
attachment.setUploadProgress(progress)
})
if (attachment.file) {
const upload = new AttachmentUpload(attachment, target)
upload.start()
}
}
const directUpload = new DirectUpload(attachment.file, directUploadUrl, delegate)
directUpload.create((error, attributes) => {
if (error) {
console.warn("Failed to store file for attachment", attachment, error)
} else {
const sgid = attributes.attachable_sgid
const url = blobUrlTemplate
.replace(":signed_id", attributes.signed_id)
.replace(":filename", encodeURIComponent(attributes.filename))
attachment.setAttributes({ sgid, url })
}
})
})