Skip to content

Instantly share code, notes, and snippets.

@petebytes
Forked from TheRealNeil/_photo.json.jbuilder
Created October 20, 2019 18:24
Show Gist options
  • Save petebytes/7c76430c2bb873fcb25a2db5565592b9 to your computer and use it in GitHub Desktop.
Save petebytes/7c76430c2bb873fcb25a2db5565592b9 to your computer and use it in GitHub Desktop.
Using the Trix Editor plus Private File Upload Attachments to S3
json.extract! photo, :id, :image_data, :created_at, :updated_at
json.url photo_url(photo, format: :html)
json.image_url image_url_photo_url(photo)
class PhotosController < ApplicationController
before_action :set_photo, only: [:show, :edit, :update, :destroy, :image_url]
...
def image_url
redirect_to @photo.image.url
end
...
end
Rails.application.routes.draw do
...
resources :photos do
get "image_url", on: :member
end
...
end
// Turn off the default Trix captions
Trix.config.attachments.preview.caption = {
name: false,
size: false
};
function uploadAttachment(attachment) {
var options = {
extension: attachment.file.name.match(/(\.\w+)?$/)[0], //Set the file extension
_: Date.now() //Prevent Caching
};
$.getJSON("/images/upload/cache/presign", options, function(result) {
// Create our form data to submit
var file = attachment.file;
var form = new FormData;
form.append("key", result['fields']['key']);
form.append("policy", result['fields']['policy']);
form.append("x-amz-credential", result['fields']['x-amz-credential']);
form.append("x-amz-algorithm", result['fields']['x-amz-algorithm']);
form.append("x-amz-date", result['fields']['x-amz-date']);
form.append("x-amz-signature", result['fields']['x-amz-signature']);
form.append("file", file);
// Create our XHR request
var xhr = new XMLHttpRequest;
xhr.open("POST", result['url'], true);
// Report file uploads back to Trix
xhr.upload.onprogress = function (event) {
var progress = event.loaded / event.total * 100;
attachment.setUploadProgress(progress);
}
// Tell Trix what url and href to use on successful upload
xhr.onload = function () {
if (xhr.status === 204) {
var image = {
id: result['fields']['key'].match(/cache\/(.+)/)[1],
storage: "cache",
metadata: {
size: attachment.filesize,
filename: attachment.filename,
mime_type: attachment.contentType
}
};
rails_form = new FormData;
rails_form.append("photo[image]", JSON.stringify(image));
$.ajax("/photos", {
contentType: false,
processData: false,
data: rails_form,
method: 'POST',
dataType: 'json'
}).done(function(data){
return attachment.setAttributes({
url: data.image_url,
href: data.url
})
});
}
}
return xhr.send(form);
});
}
// Listen for the Trix attachment event to trigger upload
document.addEventListener("trix-attachment-add", function(event) {
var attachment = event.attachment;
if (attachment.file) {
return uploadAttachment(attachment);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment