How to Upload a Local File to a Carrierwave Model

How to upload a local file to a Carrierwave model?

@user = User.first
image_path = "/tmp/pic-s7b28.jpg"

@user.image = File.open(image_path)
@user.save!

You can check examples in the carrierwave readme

Manually upload and save files in Carrierwave

Try this

@attachments.each do |attachment|
begin
options = {
:project_id => attachment.ProjectID,
:name => attachment.Description,
:user_id => attachment.UserId,
:created_at => attachment.CreatedDate,
:updated_at => attachment.LastModifiedDate,
:file => File.new(File.join("/home/username/Attachments/",attachment.Filename))
}

new_attachment = Attachment.new(options)


new_attachment.save!

puts "Attachment added successfully "

rescue => error
puts "Error migrating Attachment: #{error}"
end
end

Perhaps that would do for you as carrierwave would internally call store! for you

Question?

Failed to manipulate with rmagick, maybe it is not an image? Original Error: no decode delegate for this image format

Not sure what are you trying to over here because you have define an image? method which is not specified in condition also is that something that you want the content_type to be only present for image file

if no perhaps only the process call would work

process :set_content_type

if yes then perhaps you have to do something like this

process :set_content_type , :if => :image?

def image?(new_file)
%w(jpg jpeg gif).include?(new_file.extension)
end

Hope this help

EDIT based upon the comment

try this just used the condition same logic

   version :thumb ,:if => image? do
// your code
end



Upload file with api and carrierwave

Basically it is based on the tool which is used by the API consumer. If API consumer is using ruby then can consume it by passing File object, or using httmultiparty gem we can upload the file.

For you reference https://github.com/jwagener/httmultiparty. Please let me know if you need more help.

Carrierwave file upload with different file types

You should try using like this

class FileUploader < CarrierWave::Uploader::Base  
include CarrierWave::MiniMagick

process :process_image, if: :image?
process :process_pdf, if: :pdf?

protected

def image?(new_file)
new_file.content_type.start_with? 'image'
end

def pdf?(new_file)
new_file.content_type.start_with? 'application'
end

def process_image
# I process image here
end

def process_pdf
# I process pdf here
end
end


Related Topics



Leave a reply



Submit