How can allow to use upload only some kind of files, for example only PDF, Word or Excel files?
I use Paperclip gem.
Use content_type validation, like here:
validates_attachment :avatar, :content_type => { :content_type => "application/pdf" }
Related
How can I change the path of the images I upload using paperclip and rails. I want the path to be inside my bucket's gov_id folder and the image just stays there without any subfolders. And also how to make the url of the image to follow this format: "https://s3-ap-southeast-1.amazonaws.com/BUCKET_NAME/GOV_ID/IMAGE_NAME.EXTENSION"
Note: I have a gov_id folder inside my bucket
I have an attachment model that looks like this:
class Attachment < ApplicationRecord
belongs_to :attachable, polymorphic: true
has_attached_file :image, :styles => {:thumb => "200x200#"},
:storage => :s3,
validates_attachment :image, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png"] }
validates_attachment :image, presence: true
before_save :rename_file
def rename_file
extension = File.extname(image_file_name).gsub(/^\.+/, '')
new_image_file_name = "gov_#{self.attachable.reference_code}.#{extension}"
image.instance_write(:file_name, new_image_file_name)
end
end
this stores the image uploaded to my bucket but not inside the gov_id folder. It goes to attachments/images/000/000/013/original
And the url becomes "s3-ap-southeast-1.amazonaws.com/BUCKET_NAME/attachments/images/000/000/013/original/gov_UG2S463C.png?1500620951
The problem is that you are trying to assign it a new name and succeeding, but you aren't telling it to do this in a format that s3 understands.
The thing you have to remember, is that s3 buckets work based on keys and objects. If you look at an s3 bucket, the folder structure is just for show, for the most part. The file path (including the file name) is essentially the key, and the object is the image stored there (in this case).
So, the key you are assigning the image is the default paperclip path (source:
paperclip docs), which ends in :file_name
in this block
has_attached_file :image, :styles => {:thumb => "200x200#"},
:storage => :s3,
You have a comma at the end of your has_attached_file, which I assume means you deleted things like bucket_name: (which is fine, but next_time, replace any sensitive info with a placeholder name. it makes the problem easier to understand).
You should have a path: symbol associated with the key used to access the s3 object. Usually, paperclip auto-generates this for you, but here you want to manually assign it. So you should be able to add something like this:
has_attached_file :image, :styles => {:thumb => "200x200#"},
:storage => s3,
:path => "/gov_id/:class/:attachment/:style/:file_name"
If you would like the '000/000/001' then put :path => "/gov_id/:class/:attachment/:id_partition/:style/:file_name"
I assume you want to have style in there so that it will deal with both the :original and :thumb style appropriately.
Also, instead of using a before_save, you might want to look into Paperclip.interpolates
something like:
has_attached_file :image, :styles => {:thumb => "200x200#"},
:storage => s3,
:path => "/gov_id/:class/:attachment/:style/:replaced_file_name"
Paperclip.interpolates :replaced_file_name do
extension = File.extname(image_file_name).gsub(/^\.+/, '')
new_image_file_name = "gov_#{self.attachable.reference_code}.#{extension}"
new_image_file_name
end
I had successfully integrated comfortable mexican sofa CMS into an existing rails 4.1.2 application.
Now I want to upload images to heroku from s3 bucket.
Can anyone please tell the steps for that?
Sofa is using paperclip for attachments. So first, take a look here: http://www.rubydoc.info/gems/paperclip/Paperclip/Storage/S3
Then in initializers/comfortable_mexican_sofa.rb you'll find config.upload_file_options. This is how you'll override defaults.
config.upload_file_options = {
:storage => :s3,
:s3_credentials => ...
}
config.upload_file_options = {
:whiny => false,
:storage => :s3,
:s3_credentials => {"access_key_id" => ENV["S3_ACCESS_KEY_ID"], "secret_access_key" => ENV["S3_SECRET_ACCESS_KEY"]},
:bucket => ENV["S3_BUCKET_NAME"],
:s3_host_name => 's3 HOST NAME',
:path => "uploaded_files/:basename.:extension",
:styles => {:thumb => "850x850>" }
}
Give styles inside the config.upload_file_options which will take exact size of an image.
Which make more sense in uploading image else image pixels may vary.
The available configuration parameters are defined in paperclip, not comfy, and more information about there meaning can be found at:
http://www.rubydoc.info/github/thoughtbot/paperclip/Paperclip/Storage/S3
Just a note: Comfy has switched from Paperclip to ActiveStorage in 2017, so the answers are somewhat outdated.
I am trying to batch-upload images to Redmine and link them each to a certain wiki pages.
The docs (Rest_api, Using the REST API with Ruby) mention some aspects, but the examples fail in various ways. I also tried to derive ideas from the source - without success.
Can anyone provide a short example that shows how to upload and link an image from within Ruby?
This is a bit tricky as both attachments and wiki APIs are relatively new, but I have done something similar in the past. Here is a minimal working example using rest-client:
require 'rest_client'
require 'json'
key = '5daf2e447336bad7ed3993a6ebde8310ffa263bf'
upload_url = "http://localhost:3000/uploads.json?key=#{key}"
wiki_url = "http://localhost:3000/projects/some_project/wiki/some_wiki.json?key=#{key}"
img = File.new('/some/image.png')
# First we upload the image to get attachment token
response = RestClient.post(upload_url, img, {
:multipart => true,
:content_type => 'application/octet-stream'
})
token = JSON.parse(response)['upload']['token']
# Redmine will throw validation errors if you do not
# send a wiki content when attaching the image. So
# we just get the current content and send that
wiki_text = JSON.parse(RestClient.get(wiki_url))['wiki_page']['text']
response = RestClient.put(wiki_url, {
:attachments => {
:attachment1 => { # the hash key gets thrown away - name doesn't matter
:token => token,
:filename => 'image.png',
:description => 'Awesome!' # optional
}
},
:wiki_page => {
:text => wiki_text # original wiki text
}
})
I am a newbie. I am trying to upload an image through paperclip. The url and path code is working but the style option is not working. This is my code:
class User < ActiveRecord::Base
has_attached_file :image, :styles => { :small => "150x150>" },
:url => "/assets/users/:id/:style/:basename.:extension",
:path => ":rails_root/public/assets/users/:id/:style/:basename.:extension"
end
When I use the style it doesn't work. If I remove the style option it does work. Please help me out!
Not sure if this will work but try :style_:basename.:extension
I want to have Rack serve a specific file with a specific content type. It's a .htc file and it needs to be served as text/x-component so that IE will recognize it. In apache I would just do
AddType text/x-component .htc
How can I achieve this with Rack? Currently the file is served by Rack::Static, but I didn't find an option to set the content type.
You can update your config/initializers/mime_types.rb like this:
# Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register_alias "text/html", :iphone
Rack::Mime::MIME_TYPES.merge!({
".ogg" => "application/ogg",
".ogx" => "application/ogg",
".ogv" => "video/ogg",
".oga" => "audio/ogg",
".mp4" => "video/mp4",
".m4v" => "video/mp4",
".mp3" => "audio/mpeg",
".m4a" => "audio/mpeg",
".htc" => "text/x-component"
})
Or just to reply to the question, add this in config/initializers/mime_types.rb:
Mime::Type.register "text/x-component", :htc