Uploading Pictures Ruby on Rails
Paperclip is quite awesome. There's an excellent RailsCast about it - http://railscasts.com/episodes/134-paperclip
Looking to display picture on upload in rails
I recommends you to do it with a javascript/jquery help:
function showImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#your_preview_id')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
This code gets the image from yout input and inserts it inside the #your_preview_id
element, but, for to id, you need to do the following:
<%= f.input :avatar, :as => :file, id: "image_upload_id" %>
<%= f.button :submit, "Update", :class => "btn btn-primary" %>
Giving this id to your input, bind the change for him, and do the following:
$('#image_upload_id').on('change', function() {
showImage(this);
})
Don't forget to create a landing place for your image preview:
<div id="your_preview_id"></div>
Upload pictures with TinyMCE and RoR on protected page
You have to use the image plugin for TinyMCE and set file_picker
properties and callbacks, so you can attach files from client-side, rather than URL.
tinymce.init({
// Include image plugin on plugin list
plugins: [ 'image'],
// Include image button on toolbar
toolbar: ['image'],
// Enable title field in the Image dialog
image_title: true,
// Enable automatic uploads of images represented by blob or data URIs
automatic_uploads: true,
// URL of your upload handler
// (YOU SHOULD MAKE AN ENDPOINT TO RECEIVE THIS AND RETURN A JSON CONTAINING: {location: remote_image_url})
images_upload_url: '/text_images',
// Here we add custom filepicker only to Image dialog
file_picker_types: 'image',
// And here's your custom image picker
file_picker_callback: function(cb, value, meta) {
var input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*');
input.onchange = function() {
var file = this.files[0];
// Note: Now we need to register the blob in TinyMCEs image blob
// registry.
var id = 'blobid' + (new Date()).getTime();
var blobCache = tinymce.activeEditor.editorUpload.blobCache;
var blobInfo = blobCache.create(id, file);
blobCache.add(blobInfo);
// Call the callback and populate the Title field with the file name
cb(blobInfo.blobUri(), { title: file.name });
};
input.click();
}
});
Add text_images
to your route.rb
file:
match "text_images" => "text_images#create", via: :post
And create your proccessing action like this:
def create
if params[:file].class == ActionDispatch::Http::UploadedFile
@image = Picture.new(image: params[:file])
respond_to do |format|
if @image.save
format.json { render json: { "location": @image.image.url }.to_json, status: :ok }
else
format.json { render json: @image.errors, status: :unprocessable_entity }
end
end
end
end
This is a very crude implementation, you should make it more secure for your application context, validating and filtering large or invalid files!
UPDATE: There was a recent upgrade on the syntax for new versions of TinyMCE for the onchange
function to include a result reader attribute on the create method of the blobCache
object:
input.onchange = function() {
var file = this.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
// Note: Now we need to register the blob in TinyMCEs image blob
// registry. In the next release this part hopefully won't be
// necessary, as we are looking to handle it internally.
var id = 'blobid' + (new Date()).getTime();
var blobCache = tinymce.activeEditor.editorUpload.blobCache;
var blobInfo = blobCache.create(id, file, reader.result);
blobCache.add(blobInfo);
// call the callback and populate the Title field with the file name
cb(blobInfo.blobUri(), { title: file.name });
};
};
How to store private pictures and videos in Ruby on Rails
I would have Paperclip use S3 on the back-end, set uploaded files to private, and then use "Query String Request Authentication Alternative" to generate the URLs for my image tags.
http://docs.amazonwebservices.com/AmazonS3/2006-03-01/index.html?RESTAuthentication.html
Uploading multiple pictures per object
Read the guide you linked again, you need to use fields_for
for the child item component of the form:
<%= form_for(@post, :html => { :multipart => true }) do |f| %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<%= f.fields_for :post_attachments do |p| %>
<div class="field">
<%= p.label :avatar %><br>
<%= p.file_field :avatar, :multiple => true, name: "post_attachments[avatar][]" %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
So in your case, more like:
<%= form_for(@guide, html: { multipart: true }) do |f| %>
<%= f.fields_for :post_attachments do |p| %>
<div class="picture" style="float:left;">
<%= p.file_field :picture %>
</div>
<% end %>
<div style="">
<%= f.submit "Upload", class: "btn btn-primary edit-guide-btn" %>
</div>
<% end %>
Related Topics
Convert an Array of Integers into an Array of Strings in Ruby
Find() with Nil When There Are No Records
Iconv Deprecation Warning with Ruby 1.9.3
How to Remove Ruby from Ubuntu
Ruby Rails - Select Only Few Columns from the Data Base
Emacs Ruby-Mode Indentation Behavior
Ruby: Conditional Matrix? Case with Multiple Conditions
How to Use the Rails Helper "Distance_Of_Time_In_Words" in Plain Old Ruby (Non-Rails)
Best Ruby Idiom for "Nil or Zero"
Should One Use Dashes or Underscores When Naming a Gem with More Than One Word
Handling Namespace Models (Classes) in Namespace
How to Install Ruby-Debug in Ruby 1.9.3/Rails 3.2.1