I have at base64 encoded string of a image file. I need to save it using Paper Clip
My Controller code is
#driver = User.find(6)
encoded_file = Base64.encode64(File.open('/pjt_path/public/test.jpg').read)
decoded_file = Base64.decode64(encoded_file)
#driver.profile_pic = StringIO.open(decoded_file)
#driver.save
In my user model
has_attached_file :profile_pic, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => '/icon.jpg'
Currently the file is saved as a text file(stringio.txt). But when I change the extension to JPG I can view it as image. How can I name the image correctly using StringIO.
I am having rails 3.2, ruby 1.9.2, paperclip 3.0.3
I fixed the issue by using
encoded_file = Base64.encode64(File.open('/pjt_path/public/test.jpg').read)
decoded_file = Base64.decode64(params[:encoded_image])
begin
file = Tempfile.new(['test', '.jpg'])
file.binmode
file.write decoded_file
file.close
#user.profile_pic = file
if #user.save
render :json => {:message => "Successfully uploaded the profile picture."}
else
render :json => {:message => "Failed to upload image"}
end
ensure
file.unlink
end
Try setting the :path/:url option of has_attached_file and explicitly overriding the extension:
http://rdoc.info/gems/paperclip/Paperclip/ClassMethods#has_attached_file-instance_method
respectively
http://rdoc.info/gems/paperclip/Paperclip/Storage/Filesystem
Related
I would like to restrict File uploads to images only, and convert them automatically to .png. To do so, I use this class:
class ImageAttachment < ActiveRecord::Base
attr_accessible :file, :file_file_name, :file_content_type, :file_file_size
validates_attachment :file,
:content_type => { :content_type => ["image/jpg", "image/tiff", "image/png"] }
has_attached_file :file,
:styles => { :original => ["100%", :png],
:large => ["500x500", :png],
:medium => ["150x150", :png],
:thumb => ["75x100", :png]
},
:default_url => "/system/missing_thumb.png"
end
As I understand, the :styles => { :original => ["100%", :png], ...} should convert all uploaded files that pass validation to .png files. Therefore, I expect the following things to happen when uploading a file example.tiff:
convert the file to .png
change the file name accordingly to example.png
change the content type accordingly to "image/png"
Here's a spec I use:
it "should convert all image types to .png" do
test_file = File.new(Rails.root + "spec/fixtures/images/test.tiff")
attachment = ImageAttachment.create :file => test_file
attachment.file.url.should == "some/paperclip/path/.../test.png"
attachment.file_file_name.should == "test.png"
attachment.file_content_type.should == "image/png"
end
The first assertion is true, and I can also see ImageMagick output in the terminal,
but attachment.file_file_name still returns example.tiff, and attachment.file_content_type returns "image/tiff".
Is my assumption that paperclip automatically updates the file_file_name and the file_content_type attributes wrong?
If so, how would I best do this on my own?
I'm trying to upload an image using paperclip and the AWS S3 storage
I've set the default configuration for paperclip
config.paperclip_defaults = {
:storage => :s3,
:bucket => '<bucket_name>',
:s3_credentials => Rails.root.join('config', 'aws.yml').to_s
}
In my model i have this
as_attached_file :img, :styles => { :medium => "300x300>", :thumbnail => "100x100>" }, :path => "assets/products/:attachment/:id/:style.:extension"
In the controller i have a simple property update because my model is first created and after the images are uploaded :
def upload_thumbnail
#product = Product.find(params[:id])
if #product.update_attribute(:img, params[:image])
render :json => { :done => true, :img_path => #product.img.url }
else
render :json => #product.errors }
end
end
When i upload an image i get in the console this error
[paperclip] Saving attachments.
[paperclip] saving assets/products/imgs/10/original.jpg
[AWS S3 200 4.134236 3 retries] put_object(:acl=>:public_read,:bucket_name=>"<bucket_name>",:content_length=>0,:content_type=>"image/jpeg",:data=>Paperclip::UploadedFilAdapter: image.jpg,:key=>"assets/products/imgs/10/original.jpg") AWS::Core::Client::NetworkError AWS::Core::Client::NetworkError
Looking in S3 the image is created at the path specify by has the size set to 0 bytes.
Also I've notice that i get this when the plugin is trying to resize the image
[paperclip] Error while determining content type: Cocaine::CommandNotFoundError
but the original image should be uploaded correct.
What i'm doing wrong ?
I wrote a rake task that downloads an image from wikipedia given a celebrity name, but for some reason when storing on S3 the file extension is either being dropped or changed to .txt
The file otherwise is correct.
Any ideas?
From my celeb model:
has_attached_file :pic,
:styles => { :medium => "300x300>", :thumb => "100x100>" },
:default_style => :medium,
:storage => :s3,
:s3_credentials => "#{Rails.root}/config/s3.yml",
:path => "/:style/:img_name.:extension"
From my rake task:
desc "Update celeb pics from wiki"
task :update_celeb_pics => [:environment] do
include ApplicationHelper
Celeb.all.each do |celeb|
if !celeb.name.start_with?("(")
puts celeb.name
celeb.pic = open(getImage(celeb.name))
celeb.save
end
end
end
the getImage method is a helper that returns a string
require 'open-uri'
require 'uri'
module ApplicationHelper
def getInfo(name)
Nokogiri::XML(open(URI.escape("http://en.wikipedia.org/w/api.php?action=opensearch&search=#{name}&limit=1&namespace=0&format=xml")))
end
def nokoPage(name)
Nokogiri::XML(open(getURL(name)))
end
def getImage(name)
"http:" + nokoPage(name).css("table img")[0].attribute("src").value if !nokoPage(name).css("table img").empty?
end
def getDescription(name)
getInfo(name).css("Description").text
end
def getURL(name)
getInfo(name).css("Url").text
end
def getBday(name)
bday = nokoPage(name).css("span.bday")
return Date.parse(bday[0].text) if !bday.empty?
return Date.today
end
def getDday(name)
dday = nokoPage(name).css("span.dday")
return Date.parse(dday[0].text) if !dday.empty?
end
end
This is because
self.pic = open("http://something.com/bla/image.png")
is not the best solution here. Just yesterday, i got a Pull Request merged into Paperclip that lets you do this
self.pic = URI.parse(getImage(name))
This will ensure that your pic's content type matches the downloaded file, pic's filename is set to the name of the file downloaded.
The reason you get txt extension is because open returns a StringIO object which infact names the filename as "stringio.txt". Your filename is probably changed by the s3 code but the extension remains as '.txt'
I suggest you link your Gemfile to paperclip's github repo, run bundle and try again.
Cheers,
Aditya
Here I have Controller
require 'open-uri'
user = User.new
url = "some_remote_image.jpg" #remote image WITH extension
user.image = open(url)
user.save
Model
has_attached_file :image,
:styles => { :thumb => "25x25>", :large => "1000x1000>" },
:path => ":rails_root/images/users/:id/:style/:hash.:extension",
:url => "/images/users/:id/:style/:hash.:extension",
:hash_secret => "hash string"
This work, but images stores without extension, for ex. "some_remote_image."
If uploading images by post form everything uploading WITH extension.
I'm confused.
I solved it by updating Paperclip to last github version and set image like this instead of user.image = open(url)
user.image = URI.parse(url)
In case if someone wants reverse thing - add extension to no extension files
def besfore_save
tempfile = data.queued_for_write[:original]
unless tempfile.nil?
extension = File.extname(tempfile.original_filename)
if !extension || extension == ''
mime = tempfile.content_type
ext = Rack::Mime::MIME_TYPES.invert[mime]
self.data.instance_write :file_name, "#{tempfile.original_filename}#{ext}"
end
end
true
end
I'm using Paperclip 2.3.5 within a Rails app to store PDF documents on Amazon S3. For every PDF a JPG thumbnail is generated by ImageMagick. Im' using this configuration in the model:
has_attached_file :file,
:styles => { :thumb => { :geometry => "200x200>",
:format => :jpg
} },
:whiny => false,
:storage => :s3,
:s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
:s3_permissions => 'authenticated-read',
:s3_headers => { 'Expires' => 1.year.from_now.httpdate },
:url => "s3.amazonaws.com",
:path => "documents/:id/:style/:basename.:extension",
:bucket => 'mybucket'
But there is problem: The generated thumbnail is uploaded to S3 with the content_type "application/pdf", which is WRONG, because it's a JPG (you can see the content_type of a file on S3 with a S3 exploring tool like Cyberduck). For the original PDF file this content_type is correct, but not for the thumbnail. This causes trouble in some browsers (e.g. Chrome or Safari) which don't show the thumbnail inline.
Beware: The content_type stored in my database (field "file_content_type") is "application/pdf", which is still correct, because it's the content_type for the original file.
How can I override the content_type for a thumbnail if it should be different from the original file?
This is how we fixed it on brighterplanet.com/research, which has pdf documents and png previews:
has_attached :pdf_document,
:storage => :s3,
# [... other settings ...]
# PDFs work better in Windows 7 / IE if you give them content-type: attachment
:s3_headers => { 'Content-Disposition' => 'attachment' },
:styles => { :preview => { :geometry => '135', :format => :png } }
after_save :fix_thumbnail
def fix_thumbnail(force = false)
# application/pdf and application/x-pdf have both been seen...
return unless force or pdf_document_content_type.include?('pdf')
# set content type and disposition
s3 = AWS::S3.new(YAML.load(File.read("#{RAILS_ROOT}/config/aws_s3.yml")))
t = s3.buckets[PAPERCLIP_BUCKET].objects[pdf_document.path(:thumbnail)]
content = t.read
t.write(:data => content, :content_type => 'image/png', :content_disposition => 'inline', :acl => :public_read)
nil
end
I had to overcome this, not the most elegant solution but I forked Paperclip and hold the patch in my own git repo - https://github.com/svetzal/paperclip
It is a direct replacement for Paperclip, just put in your environment.rb
gem 'twm_paperclip', :lib => 'paperclip'
This is fixed in paperclip >= 2.7, as you can see here:
https://github.com/thoughtbot/paperclip/blob/v2.7/lib/paperclip/storage/s3.rb#L290
the mime-type of the file that is written to S3 is determined specifically before uploading.