How to upload an image to S3 using paperclip gem - ruby-on-rails

For the life of my I can't understand how the basic paperclip example works. There's only one line included in the controller, and that's
#user = User.create( params[:user] )
I simply don't understand how that's all that is needed to upload an image to s3. I've changed the example quite a bit because i wanted to use jquery file uploader rather than the default rails form helper, so I'm at the point where an image is being POSTed to my controller, but I can't figure out how I'm supposed to take the image from the params and assign it as an attachment. Here's what I'm seeing the logs:
Parameters: {"files"=>[#<ActionDispatch::Http::UploadedFile:0x132263b98 #tempfile=#<File:/var/folders/5d/6r3qnvmx0754lr5t13_y1vd80000gn/T/RackMultipart20120329-71039-1b1ewde-0>, #headers="Content-Disposition: form-data; name=\"files[]\"; filename=\"background.png\"\r\nContent-Type: image/png\r\n", #content_type="image/png", #original_filename="background.png">], "id"=>"385"}
My JS is very simple:
` $('#fileupload').fileupload({
dataType: 'json',
url: '/my_url',
done: function (e, data) {
console.log('done');
}
});`
What would be helpful for me to know is how I can strip the file data from the POSTed parameters given above and pass it to paperclip. I'm sure that I'll have to assign the attachment attribute a value of File.open(...), but I dont know what source of my file is.
I've spent a ridiculous amount of time trying to figure this out and I can't seem to get it. I've tried uploading directly to s3, but the chain of events was terribly confusing, so I want to get this simple pass-through example completed first. Thanks so much for any help you cna give!

You need a few more pieces and it will help if you can show the exact code you're using.
Paperclip can post to S3 by using:
http://rubydoc.info/gems/paperclip/Paperclip/Storage/S3
When your controller creates a User model, it is sending along all the params. This is called "mass assignment" (be sure to read about attr_accessible).
When your model receives the params, it uses the Paperclip AWS processor, which uploads it.
You need the AWS gem, a valid bucket on S3, and a config file.
Try this blog post and let us know if it helps you:
http://blog.trydionel.com/2009/11/08/using-paperclip-with-amazon-s3/
UPDATE 2013-04-03: Pleases see Chloe's comment below-- you may need an additional parameter, and the blog post may be outdated.

If you want to do it manually, approach it like this:
# In order to get contents of the POST request with the photo,
# you need to read contents of request
upload = params[:file].is_a(String)
file_name = upload ? params[:file] : params[:file].original_filename
extension = file_name.split('.').last
# We have to create a temp file which is going to be used by Paperclip for
# its upload
tmp_file = "#{Rails.root}/tmp/file.#{extension}"
file_id = 0
# Check if file with the name exists and generate unique path
while File.exists?(tmp_file) do
tmp_file_path = "#{Rails.root}/tmp/file#{file_id}.#{extension}"
id += 1
end
# Let's write the file from post request to unique location
File.open(tmp_file_path, 'wb') do |f|
if upload
f.write request.body.read
else
f.write params[:file].read
end
end
# Now that file is saved in temp location, we can use Paperclip to mimic one file
# upload
#photo = Photo.new :photo => File.open(tmp_file_path)
# We'll return javascript to say that the file is uploaded and put its thumbnail in
# HTML or whatever else you wanted to do with it
respond_to do |format|
if #photo.save
render :text => "Success"
else
render :text => #photo.errors
end
end
You can rewrite your create or whatever you use as the url to which you are POSTing the form.

This bit:
"files"=>[#<ActionDispatch::Http::UploadedFile:0x132263b98 #tempfile=# <File:/var/folders/5d/6r3qnvmx0754lr5t13_y1vd80000gn/T/RackMultipart20120329-71039-1b1ewde-0>
is the part (I think) that holds the file contents that are posted in the form.
In Rails, the User model will have a helper: has_attached_file
Passing the [:params] to the User.create method allows that helper to pick up the file contents, do any processing on them (eg resizing etc based on attributes supplied to the helper) and then push the image(s) to your storage (eg S3 or whatever - S3 credentials are passed to the helper).
Hopefully that explains the 'how does it do it?' question
re the jQuery bit.. not sure what the code should be there, but why not use the Rails form with :remote => true and handle the response in jquery?

Related

Rails - save image to active storage using signature_pad js / toDataUrl canvas method

I am creating images using signature pad (signature pad allows the user to draw or "sign" and creates an image of the signature for you).
Signature pad creates an image using the toDataURL() javascript method (see here).
I'm trying to attach this image (which I am calling "signature") to my Doc model using an html.erb form and active storage.
Here is my model:
class Doc < ApplicationRecord
has_one_attached :signature
end
and here is a some of the html / javascript:
<%= f.hidden_field :signature, id: "signature_input", value: nil %>
<script>
// create image and attach to input field when the user submits the form.
// The ".toDataUrl()" create a data url image - this is where I'm struggling. I'm not familiar with data url images
$('#signature_input').val(signature_pad.toDataURL());
</script>
here's my controller (I think this is where I need to process the data url image and store with active storage... but I'm really struggling here)
class DocSignaturesController < ApplicationController
def update
# find doc
#doc = Doc.find(params[:id])
# assign the update params. NOTE: after assigning the "signature" the #doc will no longer be valid
#doc.assign_attributes(update_params)
# saving causes error: "ActiveSupport::MessageVerifier::InvalidSignature (ActiveSupport::MessageVerifier::InvalidSignature):"
#udoc_signature.save
end
private
def update_params
params.require(:doc).permit(:signature)
end
end
I think the way my form and javascript are set up, the "signature" image could be saved as a binary attribute on the Doc model directly to the database (I have not tried this, but this is what the tutorial I'm working through shows). However, with active storage, it is not working.
I've been able to upload images to active storage from other views (using rails f.file_field inputs) but I'm having trouble with the data url and f.hidden_field input.
Any help would be greatly appreciated!
Thanks

Associating a file uploaded with Carrierwave_Direct with an object

I'm uploading files directly to S3 using the carrierwave_direct gem and everything is going smoothly. However, when amazon redirects back to the URL specfied in success_action_redirect, I'm not associating the uploaded file with the object.
My controller looks like
def edit
#excel_version = ExcelVersion.find(params[:id])
#uploader = #excel_version.excel_everest_macro
#uploader.success_action_redirect = edit_admin_excel_version_url
end
def update
#excel_version = ExcelVersion.find(params[:id])
#excel_version.assign_attributes(params[:excel_version])
#excel_version.save
end
And I have a hidden form field in my view that looks like
= form_for #excel_version do |form|
= form.hidden_field :key
So in my update action I just use #excel_version.assign_attributes(params[:excel_version])
and the key returned by Amazon makes it into the model just fine. However, the uploader mounted on the #excel_version object doesn't get url and I can't set up a link to then download the file.
Any suggestions on how I can use the S3 parameters returned to me to associate the file with the model as carrierwave would normally do?
Thanks!
P.S. another answer on here suggested reading the carrier_wave direct documentation on github, which I have and have found unhelpful in this respect.
To associate the image to the model what you can do is create a method in your controller which would use the params from amazon and create the image link
For example you can do -
def image_url
respond_to do |format|
format.json { render :json => { :filelink => "https://s3.amazonaws.com/#{params[:bucket]}/#{params[:key]}" } }
end
end
What this code will do is when amazon does a success redirect to image_url method it will use the parameters "bucket" and "key" to create a exact link to your image. (The params which are sent have both key and the bucket name)
Now you can put this image url in the hidden object on your view so that when the form is posted to the server the url also gets posted along with it. Which you can associate to your model.
Hope this helps. It worked for me.
So my problem was that I had the hidden_field :key field on the wrong form. I mistakenly put the field on the direct_upload_form_for #uploader form that uploads the file to S3.
Of course, you need the :key field on a form that the user returns to after posting the file to S3 (ie at the url passed in to the success_action_redirect method). It is there that S3 will return the key in the params and you can associate it with your model.
Thanks for all the helpful suggestions!

getting text from file uploaded with paperclip

I've got a very simple file upload for a text file using paperclip.
What I want to do is to get the first line of the text file and turn it into a hash I can search against in a database.
I don't think it makes much sense to save the file, then retrieve it, create the hash, and then save it again.
I can't seem to figure out how to get the text of the attached file before saving.
my controller is fairly simple at the moment
def create
#upload = Upload.new(params[:upload])
#upload.user_id=current_user.id
#get the first line of the uploaded file
if #upload.save
redirect_to #upload, :notice =>'Successfully uploaded file."
else
render :action => 'new'
end
end
Going through the documentation, I've seen that paperclip has a to_tempfile, which I assume I can read into a string, but i can't seem to find anywhere that shows me how to do that.
If params[:upload] is the file_field_tag in your form, then it's easier to bypass Paperclip and retrieve the first line of the file directly using Rails, just do this:
first_line = params[:upload].tempfile.readline

Paperclip & Rails Api

I have a photo rails app using paperclip. My model called photo and the request parameter also photo.So when i am trying to upload via curl i use : curl -F "photo[photo]=#/pics/pic.jpg" http://something/photos.xml .
That's works fine! How can i change the photo[photo] parameter to "photo" or "media" or something else? How can i change the endpoint url? (ex. http//something/upload.xml)
thanx!
any help will be highly appreciated, :-)
What you could do is setup another controller and work with it. What paperclip does is just setup an extra "photo" attribute and methods, thus reusing Rails .new and .update_attributes own methods. That way, when you call /photos.xml with that info, what you are doing is just a regular post photo action, with the added benefit of setting up it's picture.
When you do Object.photo = YOUR_PHOTO, you are actually using Paperclip code.
So, you could work with something like:
class ApplicationController < ActiveController::Base
def upload
photo = Photo.new
photo.photo = params[:photo]
# ... extra code
photo.save
render :text => "Ok"
end
end
And add a route like:
map.upload "/upload(.:format)", :controller => "application", :action => "upload"
(or it's Rails3 equivalent if you are using it)
That way, when you do 'curl -F "photo=#/pics/pic.jpg" http://something/upload.xml', you will invoke the upload action and create a photo using the 'photo' parameter. The photo = params[:photo] will take the tempfile you've uploaded and continue with the usual paperclip tasks :)

How do I get the base URL (e.g. http://localhost:3000) of my Rails app?

I'm using Paperclip to allow users to attach things, and then I'm sending an email and wanting to attach the file to the email. I'm trying to read the file in and add it as an attachment, like so:
# models/touchpoint_mailer.rb
class TouchpointMailer < ActionMailer::Base
def notification_email(touchpoint)
recipients "me#myemail.com"
from "Touchpoint Customer Portal <portal#touchpointclients.com>"
content_type "multipart/alternative"
subject "New Touchpoint Request"
sent_on Time.now
body :touchpoint => touchpoint
# Add any attachments the user has included
touchpoint.assets.each do |asset|
attachment :content_type => asset.file_content_type,
:body => File.read(asset.url)
end
end
end
This gives me the following error No such file or directory - /system/files/7/original/image.png?1254497688 with the stack trace saying it's the call to File.read. When I visit the show.html.erb page, and click on the link to the image, which is something like http://localhost:3000/system/files/7/original/image.png?1254497688, the image is displayed fine.
How can I fix this problem?
Typically root_url should provide this.
File.read is expecting a file path, not a url though. If you are generating the images, you should call the image generating code and return the bytes of the generated image instead of calling File.read(…)
asset.url returns the URL to the file. This is usually /system/classname/xx/xx/style/filename.ext. You'd put this in an image_tag.
You want asset.path. It returns the full path to the file, which will usually be something like /home/username/railsapp/public/system/classname/xx/xx/style/filename.ext
HTH.
request.env["HTTP_HOST"]
I don't know why this one line of code is so elusive on the web. Seems like it should be up front and center.
as ZiggyTheHamster is saying: the asset.url is the generated url that would be used on webpages (which is why you're getting the unix-style directory slashes, as pointed out in the comments.)
asset.path should give you the OS-aware path to the file, but even that isn't needed with paperclip.
Paperclip::Attachment is already an IOStream.
You just need :body => asset like so:
touchpoint.assets.each do |asset|
attachment :content_type => asset.file_content_type,
:body => asset
end

Resources