Giter Club home page Giter Club logo

carrierwave-base64's Introduction

Carrierwave::Base64

Gem Version Build Status Code Climate

Upload files encoded as base64 to carrierwave.

This small gem can be useful for API's that interact with mobile devices.

This gem requires Ruby 2.0 or higher.

Installation

Add the gem to your Gemfile:

gem 'carrierwave-base64'

Also add this if you need mongoid support:

gem "carrierwave-mongoid"

Usage

Mount the uploader to your model:

mount_base64_uploader :image, ImageUploader

Now you can also upload files by passing an encoded base64 string to the attribute. This also works for normal file uploads from file fields inside an HTML form, so you can safely replace mount_uploader with mount_base64_uploader to support both file input and base64 encoded input

Upload file extension

The file extension for the uploaded base64 string is identified automatically using the mime-types gem and content_type from the uploaded string.

If the required MIME type is not registered, you can add it, using MIME::Types#add:

MIME::Types.add(
  MIME::Type.new('application/icml').tap do |type|
    type.add_extensions 'icml'
  end
)

Setting the file name

You can set the file_name option to a lambda, that will return a filename without an extension, using the model instance:

mount_base64_uploader :image, ImageUploader, file_name: -> (u) { u.username }

[DEPRECATED: Settings this option to a string is deprecated, if you still want to set the filename to a fixed string, wrap it in a Proc] To set the file name for the uploaded files, use the :file_name option (without extention):

# Deprecated way:
mount_base64_uploader :image, ImageUploader, file_name: 'userpic'

# New way
mount_base64_uploader :image, ImageUploader, file_name: -> { 'userpic' }

Data format

File extention for the uploaded file is identified automatically based on the file contents. If it can't be identified automaticaly, it falls back to the content-type, specified in the data string.

data:image/jpeg;base64,(base64 encoded data)

Contributing

  1. Fork it ( https://github.com/[my-github-username]/carrierwave-base64/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

carrierwave-base64's People

Contributors

aligit avatar demetrodon avatar detournemint avatar dustmason avatar hendricius avatar infernalmaster avatar justisb avatar langalex avatar melcher avatar oakbow avatar princejoseph avatar quintasan avatar schinery avatar shuuuuun avatar y9v avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

carrierwave-base64's Issues

uninitialized constant CarrierWave::Mount (NameError)

Hi, I am trying carrierwave-base64 in a rails 5 api only application. I had User model with image as attribute.

I added "gem 'carrierwave-base64' " in my Gemfile and bundle it, which installed both carrierwave 1.2.2 and carrierwave-base64 2.6.1.

I generated uploader with "rails g uploader Image" to generate image_uploader.rb.

When I add " mount_base64_uploader :image, ImageUploader " to my User model It will show " uninitialized constant CarrierWave " error.

So, I searched in internet and found I need to add " require 'carrierwave/orm/activerecord " in application.rb or environment.rb.

After adding, I am not able to start rails server or rails console. It is giving error as
"module:ActiveRecord': uninitialized constant CarrierWave::Mount (NameError)".

I also tried by stopping spring but no use.

OS : Ubuntu 16.05
Database : PostgreSQL
Rails: 5.1.4
Ruby: 2.4

Element is always marked as changed, also if it's not

I just noticed that an element that has a mount_base64_uploader mounted is always marked as changed and thus saved to the DB, even when it's not changed.

It's a bit hard to describe, but let's try this.

I have a User model like this:

class User < ActiveRecord::Base
  mount_base64_uploader :file_upload,   ImageUploader
  mount_base64_uploader :string_upload, ImageUploader
end

When I edit it in a form and don't change a thing, then the following DB query is executed anyways due to the log file:

  SQL (0.3ms)  UPDATE "users" SET "string_upload" = ?, "updated_at" = ? WHERE "users"."id" = ?  [["string_upload", "file.png"], ["updated_at", "2015-10-19 15:27:10.106767"], ["id", 10]]

Here are the user_params:

$ user_params
=> {"name"=>"2haha",
 "file_upload_cache"=>"",
 "remove_file_upload"=>"0",
 "string_upload"=>"file.png",
 "string_upload_cache"=>"",
 "remove_string_upload"=>"0"
}

Notice: only the :string_upload field is written to DB, not the :file_upload, so I guess it's a problem in your gem. I think you have to check whether the sent param is only file.png and then you don't mark the attribute as changed.

While this may not be a big issue, it breaks some custom functionality of my app that relies on the fact that resources announce their changed status correctly.

You can still checkout my demo app here to see the problematic behaviour: https://github.com/jmuheim/test-carrierwave-base64-update

issue with cloudinary gem integration

Hi Guys, is it compatible with cloudinary integration? because when i change implementation from file storage to cloudinary base it doesn't work, but if i use default carrierwave gem it work.

Have to reload AR model when saving base64 photos.

Seeing a bit of odd behavior.
Gemfile.lock:

carrierwave (1.1.0)
      activemodel (>= 4.0.0)
      activesupport (>= 4.0.0)
      mime-types (>= 1.16)
    carrierwave-base64 (2.5.3)
      carrierwave (>= 0.8.0)
      mime-types (~> 3.0)

Model looks like:

 mount_base64_uploader :original_photo, PatronPhotoUploader

In a spec I have the following:

describe "#original_photo=" do
    let(:new_photo) { build(:patron_photo, original_photo: original_photo) }
    context "base64 encoded" do
      let(:original_photo) { valid_base64_image }
      it "accepts base64-encoded images" do
        expect(new_photo).to be_valid
        expect { new_photo.save! }.not_to raise_error
        expect(new_photo.original_photo).to be_present
      end
    end
  end

However, the check for presence fails.

1) PatronPhoto#original_photo= base64 encoded accepts base64-encoded images
     Failure/Error: expect(new_photo.original_photo).to be_present
       expected `#<PatronPhotoUploader:0x007f8ef4a441f8 @model=#<PatronPhoto id: 3, original_photo: "ukpu42doyhyfyov8y...Storage:0x007f8ef3ddf098 @uploader=#<PatronPhotoUploader:0x007f8ef4a441f8 ...>>, @transformation={}>.present?` to return true, got false

If I reload the active record before checking for presence it succeeds.

try to use carrierwave-base64 with nobrainer

Hi,
i would like adapt this gem with noBrainer https://github.com/y9v/carrierwave-base64 to upload a file in Base64.
So, i update this file https://github.com/y9v/carrierwave-base64/blob/master/lib/carrierwave/base64/railtie.rb
and here we can see what has been changed

module Carrierwave
  module Base64
    # Railtie class to load the carrierwave-base64 adapters
    # Loads adapters for ActiveRecord and Mongoid
    class Railtie < Rails::Railtie
      ActiveSupport.on_load :active_record do
        ActiveRecord::Base.extend Carrierwave::Base64::Adapter
      end

      ActiveSupport.on_load :mongoid do
        Mongoid::Document::ClassMethods.include Carrierwave::Base64::Adapter
      end

      ActiveSupport.on_load :nobrainer do
        puts("extending NoBrainer ...")
        NoBrainer::Document::ClassMethods.include Carrierwave::Base64::Adapter
      end
    end
  end
end

I have found ActiveSupport.onload :nobrainer when i use in console this command

irb(main):011:0> ActiveSupport.instance_variable_get(:@loaded).keys()
=> [:i18n, :after_initialize, :before_eager_load, :action_view, :active_record, :mongoid, :nobrainer, :action_controller, :before_configuration, :action_mailer, :before_initialize, :active_job, :action_dispatch_integration_test, :action_controller_base, :active_support_test_case, :action_cable, :action_cable_channel, :action_cable_connection, :action_controller_api, :devise_controller, :devise_failure_app]

and when I use

irb(main):016:0> ActiveSupport.instance_variable_get(:@loaded)[:nobrainer]
=> []

nobrainer doesn’t seem to be loaded.
Moreover, I’m using the classNoBrainer::Document::ClassMethods like it is used in https://github.com/nviennot/carrierwave-nobrainer/blob/master/lib/carrierwave-nobrainer.rb line 150.

When I start my server, I can’t see the puts message, and I have the error message “mount_base64_uploader not defined” like if ActiveSupport.on_load(:nobrainer) was not executed.

Am I missing something? Can you please help me?

Thanks for your help.

Not able to nullify file field in 2.8.0

Hi,

On 2.7.0 when I do object.image = nil I get this as a result on object.image :

#<ImageUploader:0x00007f837d3a96e0
 @cache_id=nil,
 @file=nil,
 @filename=nil,
 @format=nil,
 @model=

Since 2.8.0 I get :

#<ImageUploader:0x00007fcb04895310
 @cache_id=nil,
 @file=#<CarrierWave::Storage::Fog::File:0x00007fcb048948e8 @base=#<CarrierWave::Storage::Fog:0x00007fcb04894ff0 @uploader=#<ImageUploader:0x00007fcb04895310 ...>>, @content_type=nil, @path="development/system/campaign/22016/photo/baaa55ce-36de-40ea-85a4-9132e5ecabda.jpg", @uploader=#<ImageUploader:0x00007fcb04895310 ...>>,
 @filename=nil,
 @format=nil,
 @model=

On rails 5.1.6 with carrierwave (1.3.1)

Thanks for your work !

massive deprecation warning on rails 5.1

DEPRECATION WARNING: The behavior of changed_attributes inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after save returned (e.g. the opposite of what it returns now). To maintain the current behavior, use saved_changes.transform_values(&:first) instead. (called from block (2 levels) in <top (required)> at /home/bran/Desktop/alexandria/spec/requests/books_spec.rb:4)
DEPRECATION WARNING: The behavior of changes inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after save returned (e.g. the opposite of what it returns now). To maintain the current behavior, use saved_changes instead. (called from block (2 levels) in <top (required)> at /home/bran/Desktop/alexandria/spec/requests/books_spec.rb:4)
DEPRECATION WARNING: The behavior of changed inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after save returned (e.g. the opposite of what it returns now). To maintain the current behavior, use saved_changes.keys instead. (called from block (2 levels) in <top (required)> at /home/bran/Desktop/alexandria/spec/requests/books_spec.rb:4)
DEPRECATION WARNING: The behavior of attribute_change inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after save returned (e.g. the opposite of what it returns now). To maintain the current behavior, use saved_change_to_attribute instead. (called from block (2 levels) in <top (required)> at /home/bran/Desktop/alexandria/spec/requests/books_spec.rb:4)
DEPRECATION WARNING: The behavior of attribute_changed? inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after save returned (e.g. the opposite of what it returns now). To maintain the current behavior, use saved_change_to_attribute? instead. (called from block (2 levels) in <top (required)> at /home/bran/Desktop/alexandria/spec/requests/books_spec.rb:4)

Updating photo

I'm using this gem to upload base64 images. When I upload the image for the first time, the file upload successfully, but when updating the record and change photo, the file just won't save. Someone help me please?

The `:file_name` option set to lambda should accept the model instance as argument

The current support for lambda function set to a :file_name option is not very handy, since it has no access to the current modal instance. You can use dynamic things like current time for the filename, and that's basically it.

Let's make this option a bit more useful for the users:

class Product
  mount_base64_uploader :image, SomeUploader, file_name: -> (p) { p.slug }
end

This could be implemented by currying the lambda function with the model instance in lib/carrierwave/base64/adapter.rb:14

Combination with cocoon gem: Upload of base64 string works for creating a nested object, but not for updating it

In my project I figured out that your gem works perfectly in normal forms: I can easily upload base64 strings using a textarea, and your gem transforms it into a file. This works for both creating and updating objects.

I'm using https://github.com/nathanvda/cocoon gem which allows me to manage nested objects within the form of a parent object. Using it, it seems still to be possible upload a base64 string when creating a nested object, but when updating it, it doesn't work: it simply keeps the originally uploaded file.

I have created a test Rails app, so you can check it out: https://github.com/jmuheim/test-carrierwave-base64-update

Simply start the Rails server, and play around on localhost:3000/users:

  • Create a user and upload both a normal file and a base64 string file (I have added two base64 image strings to the form so you can simply copy&paste them)
  • Update the user and change both the normal file and the base64 string file => this works nicely
  • Now add an attachment to the user (click "add attachment" in the user form)
  • Do the same thing: add a normal and a base64 string file => works perfectly
  • Then try to update the attachment with a new file and a new base64 string => this works only for the normal file, not for the base64 file!

It would be really nice to get this to work. Any suggestion? I tried to debug, and all I can say is that it looks to me like everything seems to be passed perfectly from the form to the model, all the params look okay to me, and the base64 string seems to be passed properly to the nested object, too. But somehow it's not really saved to the disk... No idea what could be the difference between a normal and a nested update of attributes, and why create and update should be any different.

Thanks a lot for help! Tell me if I can support you in some way (e.g. writing pending specs for my dummy app which you could try to make pass).

Avatar is not saving into database

Here, I'm using latest version of carrierwave-base64 with Rails 5.0.2. Image is uploading into /public/uploads/tmp but saving nil avatar in database. Please have a look on this issue and do the needfull.

Thanks!

Error: "ArgumentError : wrong number of arguments (given 1, expected 0)"

Hi all,
After update gem version from 2.5.0 to 2.5.1.1 doesn't work uploading base64.

My stack:

rails 5.0.3
carrierwave 0.11.2
carrierwave-base64 2.5.1.1

In model:

class Profile < ApplicationRecord
  mount_base64_uploader :picture, ImageUploader
end

when I try PUT update profile with picture base64 string in format:
data:image/png;base64, `

I get error wrong number of arguments (given 1, expected 0)

Do you have any ideas what's wrong?

Thanks.

Undefined Method `strip` for File

NoMethodError: undefined method 'strip' for #<File:0x007fb46a392328> /Users/herbert/.rvm/gems/ruby-2.3.1/gems/carrierwave-base64-2.3.0/lib/carrierwave/base64/adapter.rb:14:in block in mount_base64_uploader'

I'm 'uploading' a local file in my seeds.rb in Rails 4. Get this error after bundle updating.

Net::ReadTimeout for avatar uploader

I have uploaded base64 data to carrierwave using carrierwave-base64.
When I upload this as image, I send email with this uploaded file as attachment. I have used following line to send it as attachment.

attachments[File.basename(model.avatar.url)] = open(model.avatar.url) {|f| f.read}

I am getting Net::ReadTimeout Error.How do I reduce the time to read this file?.How do I handle this situation?

Is there any support for mongoid

Hello and thanks for this nice gem
I was wondering if anything other than active record is supported? If not is there any interest that I create one for mongoid?

Best,
Ali

mimemagic dependency

As we all now, mimemagic change his license and yank all the previous versions, so it is being removed from every gem in the Rails world.

There's even a workaround fork for carrierwave: carrierwaveuploader/carrierwave#2548

Can we expect carrierwave-base64 to follow the big bro steps?

Permission denied @ unlink_internal - E:/project_name/public/uploads/1515432095-16344-0028-5553/video.mp4

Sry, I see that this is not correct place, but I cannot delete the issue.
I am getting this error when upload files. I have model Post with table posts which has a column video and model Image (table images). 1 Post has many images. The image is not required. The video is required. I have standard uploaders. This error happens ONLY if I upload more than 1 image. If I upload 1 image, everything works fine. The image and video are uploaded, data to database is saved For the view form instead 1 input for multiple images I am using many file inputs. In the table images each row is an image related to a post.
Post model:
`has_many :images

validates :video, presence: true
validates_associated :images

mount_uploader :video, VideoUploader`

Image model:
belongs_to :post mount_uploader :image, ImageUploader

ImageUploader:
`storage :file

def store_dir
"posts/images"
end

def extension_whitelist
%w(jpeg jpg)
end

def filename
"#{secure_token}.jpg" if original_filename.present?
end

def remove_original_file(p)
if self.version_name.nil?
self.file.delete if self.file.exists?
end
end
def secure_token
var = :"@#{mounted_as}_secure_token"
model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.uuid)
end`

VideoUploader:
`storage :file

def store_dir
"../videos/#{model.id}" # Not in the public directory
end

def extension_whitelist
%w(mp4)
end

def filename
"#{secure_token}.mp4" if original_filename.present?
end

def secure_token
var = :"@#{mounted_as}_secure_token"
model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.uuid)
end`

A form:
<%= form_for @post do |f| %> ..... <%= f.fields_for :images do |i| %> <%= i.file_field :image, name: 'post[images_attributes][][image]' %> ...... <%= i.file_field :image, name: 'post[images_attributes][][image]' %> <%=f.file_field :video, required: false, accept: '.mp4'%> <% end %>

posts_controller.rb:
`def new
@post= Performance.new
@post.images.build
end

def create
@post= Post.new(post_params)

if @post.save
redirect_to action: :new
else
@post.images.build if @post.images.size == 0
render :new
end
end

private
def post_params
params.require(:post).permit(:language, :name, :video, :slug,
:images_attributes => [:image])
end`
I am using Windows 10

Can mount_base64_uploader also handle normal file uploads?

I want to offer the users of my website to either use a standard input type="file" or a textarea with a base64 string.

I hoped that mount_base64_uploader would accept both kinds, but it seems it doesn't. What would you recommend to implement such a behaviour?

Permission denied @ unlink_internal [ Windows ]

When i'm trying to upload a file i get this error im running my app on Windows

Errno::EACCES (Permission denied @ unlink_internal - E:/Sites/project/public/uploads/tmp/1477749450-6708-0002-5051/file.jpg):

app/controllers/posts_controller.rb:57:in `block in create'
app/controllers/posts_controller.rb:56:in `create'

"mount_base_64_uploader" method not recognized from rails console

Hello!

I'm running into a strange thing currently, which I believe is in someway inherent to this gem, though it it possible that something is afoot in my rails environment...

The gem works flawlessly in tests, and I am able to access models with the mount_base_64_uploader on it when program execution is paused in debug statements.

However, when enter the rails console and I try to access an activerecord model which contains that uploader, it throws the following error. (the model in my case is ClientPhoto).

captura de pantalla 2018-04-16 a la s 12 54 38 p m

Any insights as to why this may be happening?

Failure when uploading docx file

When uploading a docx file which Content-Type is application/vnd.openxmlformats-officedocument.wordprocessingml.document (yes I know this looks retarded) carrierwave-base64 will fail to extract the proper media type because the regex in get_file_format method in Base64StringIO class doesn't account for dots and hyphens.

Fixing that is trivial (I will open a PR shortly) but another issue arises - namely original_filename method will blatantly paste the bit after application/ as the file extension which, in turn, will definitely fail the check in extension_whitelist in the uploader if you try listing docx there.

Could we possibly try looking up the file extension by some mime-type magic?

Uploading broken files to Amazon S3

I'm using mongoid along with carrierwave to upload files using JSON API. My controller method looks like this-

def create
    content = Content.new(content_params)     
    content.user_id = current_user.id 
    content.asset_type = content.asset.file.extension      
    if content.save      
      render json: content, status: 201, location: [:api, content] 
      ProcessAsset.perform_async(content.id.to_s) unless content.asset_type != 'pdf'
    else
      render json: { errors: content.errors }, status: 422
    end
end

Model

class Content

  include Mongoid::Document
  include Mongoid::Timestamps

  before_create :set_base_price

  mount_base64_uploader :asset, AssetUploader
  # more code
end


While the whole process works great, the file uploaded to S3 (pdf in this case) has no content in it.
I believe this has something to do with StringIO being used to read the file from the system. It sets the content_type to plain/text. This is confirmed when I download the pdf and try to open it on my system.

Here's my json I'm using to upload -
{
"content": {
"campus" : "569df3c4be84c511c0000001",
"course" : "569dfe1cbe84c511c0000006",
"subject" : "56a0c4debe84c50d2f000006",
"batch" : "2015",
"title" : "RipAndSave",
"asset": "data:application/pdf;base64,L2hvbWUvbW9qby9Eb3dubG9hZHMvc2FtcGxlLnBkZg=="
}
}

I'm using Rails 4.2, Mongoid 5.1

Can you help?

Rails 5: stored image is deleted when updating a record

When an image was uploaded to a record using base64_mount_uploader, and the record is updated, the stored image is deleted.

I have noticed this bug after upgrading an existing Rails application from 4.2.7 to 5.0.1.

I have created a working demo:

https://github.com/jmuheim/test-rails5-base64-carrierwave

Just run it and do the following to replicate:

  • Go to http://localhost:3000/users/new
  • Create a new user with a name and an avatar (copy the base64 string in the disabled textarea (data:image/png... and paste it into the "Avatar" field)
  • Hit "Create User"
  • Now you should see the user with the uploaded image:
    image
  • Now click "Edit"
  • Click "Update User"
  • Now the image has disappeared:
    image

The commit that introduces the bug is this one: jmuheim/test-rails5-base64-carrierwave@9d2f65a. It's only adding the carrierwave-base64 gem, changing 'mount_uploader' to 'mount_base64_uploader', and changing the upload field to a textarea (and providing the copy&paste string in a disabled textarea)

We are using your gem in our application on a daily base, and it's a very harmful bug to us right now. How can I help you to fix this bug as fast as possible?

Thank you for this very useful gem.

Save as JPG instead of PNG

I have the following model:

class ScreenshotUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  storage :file
  convert :jpg

  version :thumb do
    process resize_to_fill: [50, 50]
  end

  def extension_whitelist
    %w(jpg jpeg gif png)
  end

  version :print do
    process border: ['black']
    process quality: 80
  end
end

The upload of the image happens via pasting an image from the clipboard via https://github.com/layerssss/paste.js and is saved as a base64 encoded string into a <textarea>, then uploaded using the https://github.com/y9v/carrierwave-base64 gem:

class Finding < ApplicationRecord
  mount_base64_uploader :screenshot, ScreenshotUploader
end

In the HTML form, it looks like this:

image

After uploading, the result is the following files:

  • screenshot.png it's a PNG, not a JPG!
  • thumb_screenshot.jpg
  • print_screenshot.jpg

But I need the original file to be also converted to JPG, as I need to save disk space. Is there any way of doing this? I tried several methods, but none of them seems to work.

You can find more info on the StackOverflow questions:

Upload Path Issue for Base64 Updates

I am implementing an API using Grape mounted on Rails. I followed the instructions in the gem to implement the ability to upload a file using a Base64 string of an image. But the uploaded location seems to be messed up.

Upload location

  • Normally: public/uploads/customer/profile_picture/:id
  • Uploads to: public/tmp/1398957623-9523-4518

When I upload using a file it works. But when I use a base 64 string it doesn't.

* If this is a known issue, could you suggest a fix for this? If not could you give me a hint on what I might need to look at?*

Thanks in advance.

The files I think which are important are as follows:

# encoding: utf-8

class ProfilePictureUploader < CarrierWave::Uploader::Base

  include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  storage :file
  # storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  # Provides the default URL when an image is not uploaded
  def default_url
    ActionController::Base.helpers.asset_path('users/no-profile-picture.png')
  end

  version :thumb do
    process resize_to_fit: [58, 58]
  end

  def extension_white_list
    %w(jpg jpeg png)
  end

end
class User < ActiveRecord::Base
  # blah...

  # Profile picture upload
  # mount_uploader :profile_picture, ProfilePictureUploader
  mount_base64_uploader :profile_picture, ProfilePictureUploader

  # blah...
end
class AccountApi < Grape::API

  resource :account do
    # blah....

    desc 'Upload profile picture', { headers: API::HEADER_SETTINGS }
    params do
      requires :user, type: Hash do
        requires :profile_picture, type: Rack::Multipart::UploadedFile
      end
    end
    post :profile_picture do
      profile_picture = params[:user][:profile_picture]

      status = current_user.update(profile_picture: profile_picture)

      {
        uddated:  status,
        url:      current_user.picture,
        size:     profile_picture[:tempfile].size
      }
    end

    desc 'Upload profile picture (base 64)', { headers: API::HEADER_SETTINGS }
    params do
      requires :user, type: Hash do
        requires :profile_picture, type: String
      end
    end
    post :profile_picture_base64 do
      profile_picture = params[:user][:profile_picture]

      status = current_user.update(profile_picture: profile_picture)

      {
        uddated:  status,
        url:      current_user.picture,
        size:     current_user.profile_picture.size
      }
    end

  end

end

Not compatible with latest carrierwave

I have latest carrierwave gem installed in my rails 5 app and I am getting this error message while doing bundle.Please Help.


Bundler could not find compatible versions for gem "carrierwave":
  In snapshot (Gemfile.lock):
    carrierwave (= 1.0.0.beta)

  In Gemfile:
    carrierwave (< 2.0, >= 1.0.0.beta)

    carrierwave-base64 was resolved to 2.3.1, which depends on
      carrierwave (< 0.12.0, >= 0.8.0)

Running `bundle update` will rebuild your snapshot from scratch, using only
the gems in your Gemfile, which may resolve the conflict.

Uploading multiple Images using JSON API

Hi there! I need to upload multiple images to my model using the JSON API. I've been able to do it for a single image thanks to this link
https://gist.github.com/ifightcrime/9291167a0a4367bb55a2
But I've been failing at improvising the approach to upload multiple images. I'm using the the carrierwave mongoid gem along with the master branch of carrierwave and I've made the recommended changes to my model and controller. The files I'm trying to upload get stored in the cache directory but not in the intended store directory. I believe I'm not passing the file correctly to the params.
Here what my params look like just before I create an object
{"campus"=>"569df3c4be84c511c0000001", "course"=>"569dfe1cbe84c511c0000006", "subject"=>"56a0c4debe84c50d2f000006", "batch"=>"2015", "title"=>"Meteorite", "assets"=>#<ActionDispatch::Http::UploadedFile:0x00000004459ad0 @tempfile=#<Tempfile:/tmp/upload-image20160304-6427-175khj8>, @original_filename="upload-image.jpeg", @content_type=nil, @headers=nil>}
The assets key contains all information related to the files being uploaded
I've hit a dead end trying to figure this out. Please help!

Handle extensions from mime-type

With #46 closed you can upload file which mime-types don't necessarily reflect their extension. The question now is how to handle those files. The current logic goes like this:

  1. User uploads a base64 encoded docx file which has the mime-type of application/vnd.openxmlformats-officedocument.wordprocessingml.document
  2. carrierwave-base64 names the file file.extension where extension is the part occuring after the appliction/ in mime-type.
  3. That will result in a file named file.vnd.openxmlformats-officedocument.wordprocessingml.document which will definitely fail the whitelisting rule in case one writes docx there instead of vnd.openxmlformats-officedocument.wordprocessingml.document

This is hardly user-friendly. How do we fix this?

depending on mimemagic, licensing problem with GPL

carrierwaveuploader/carrierwave#2548

The gem mimemagic was previously licensed under MIT, but all existing versions were yanked this morning and replaced with new versions licensed under GPL in order to resolve a licensing issue (mimemagicrb/mimemagic#97). The Rails community is currently working to update or replace this dependency, so that Rails apps are not required to be licensed under the GPL by default (rails/rails#41750).

like Carrierwave, carrierwave-base64 has same problems with get_file_extension method.

with this problem, we can not build/deploy/release our rails applications

Supports only JPG file type

Code only supports images and specifically .jpg file types, pdfs uploaded for example are uploaded with the name "image. "

Regression on 2.6.0 when passing base64 string

I have this factory in my tests that works fine in 2.5.3 with no error:

FactoryGirl.define do
  factory :screenshot do
    file "data:image/jpeg;base64,#{Base64.encode64(File.read(Rails.root.join('spec/fixtures/images/screenshot.jpg')))}"
  end
end

With version 2.6.0 they're all failing with:

     ArgumentError:                                                                                                                                                                            
       invalid base64                                                                                                                                                                          

What am I missing?

Uploading works on create, but not on update

I want to attach screenshots to my model. Using paste.js I can paste a screenshot to a textarea, which means it puts the encoded base64 string into the textarea.

For this, I do the following, so the input isn't displayed as upload but as normal textarea (I'm using Simple Form):

= f.input :screenshot, as: :text

The cool thing is: when I create the record, the "upload" of the base64 screenshot works!

image

The sad thing is: I can't update it! When displaying the edit form, it contains the path to the file:

image

I can paste a new screenshot as expected, but the file on the harddisk doesn't get updated: it simply stays the old screenshot. There's not even an error message or something.

What did I do wrong?

unknown mimetype data:image/jpg

Hi, after upgrading from 2.3.4 to 2.4.0 i started getting this error: unknown mimetype data:image/jpg

I use the following format when uploading my base64 string: data:image/jpeg;base64,(base64 encoded data)

My current fix is to revert to 2.3.4. again but I wonder if there has been some changes in api or if this is a bug?

/Knut

Wrong data format for automatic detection. `.ai`instead of `.pdf`

When I submit a PDF file base64 encoded like this data:application/pdf;base64,JVBERi0xLjQKJfjl0MTGCjEgMCBvYmoKPDwgL........... the automatic detection change the extension from .pdf to .ai.

I use:

gem 'carrierwave', '~> 1.3.1'
gem 'carrierwave-base64', '~> 2.8.0'

Here is my code:

    file = params[:attachment][:file]
    @attachment = Attachment.new(attachment_params)
    file = file.gsub('data:application/octet-stream;base64', "data:#{@attachment.mime_type};base64")
    @attachment.attached_file = file
    @attachment.save

ps: When I submit an image base64 everything works fine.

Any idea?

NoMethodError undefined method _will_change

Hi y'all. I am not sure if this is an issue with carrierwave-base64 itself or with carrierwave itself.

I am using

root@377275e66746:/app# cat Gemfile.lock | grep carrier
    carrierwave (1.2.3)
    carrierwave-base64 (2.3.2)
      carrierwave (>= 0.8.0)

On the console I do:

myobject.update(before_image: "data:image/png;base64,......long string....")

The error I am getting is:

NoMethodError (undefined method `before_image_will_change!' for #<Servicing:0x007fb21cbb5f50>)

I read this issue on the carrierwave repo, which is from 2011, so I thought I was ok...

This is how I am defining my attribute

  mount_base64_uploader :before_image, PersistentImageUploader, mount_on: :before_image_filename

My PersistentImageUploader is

class PersistentImageUploader < ImageUploader
  configure do |config|
    config.remove_previously_stored_files_after_update = false
  end
end

And ImageUploader

class ImageUploader < BaseUploader
  process format: "jpg"
  process quality: 80
  process interlace: "plane"
  process resize_to_limit: [2000, 2000]

  def extension_white_list
    %w(jpg jpeg png)
  end
end

And BaseUploader

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

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  def filename
    return unless original_filename
    extension = MIME::Types[file.content_type].first.extensions.first

    "#{Digest::SHA1.hexdigest(file.read)}.#{extension}"
  end

  def interlace(type)
    manipulate! do |img|
      img.interlace(type.to_s)
      img = yield(img) if block_given?
      img
    end
  end

  def quality(percentage)
    manipulate! do |img|
      img.quality(percentage.to_s)
      img = yield(img) if block_given?
      img
    end
  end
end

undefined method `mount_base64_uploader' for #<Class:0x007f1f3055e8e8>

I installed the gem "gem install 'carrierwave-base64'"
I included it to my Gemfile "gem 'carrierwave-base64'"
and changed the method mount_uploader to mount_base64_uploader.

I didn't change my previous uploader class:
"class FotoUploader < CarrierWave::Uploader::Base
.....
end"

And I got this error message. How can I use carrierwave base64?

Validation fails on :file attribute

I've a strange bug which may be related to #51...?

I've a Document model with a File attribute (of type String) which is correctly set to the file name when I upload a file.

I'm trying to update an attribute on Document as follows:

d = Document.first
=> #<Document:0x00007f9eb3421478
id: "...",
file: "02a0c50a4f.pdf",
title: "My new project",
created_at: Sat, 01 Sep 2018 15:00:46 UTC +00:00>

d.update(title: 'A different title')

This works fine if I don't have validation on the File attribute, but if I include validates :file, presence: true in the Document model I get :file can't be blank.

I've been able to work around this by removing the validation but I just wondered if I'm overlooking something?

Thanks for your work on the gem 👍

Deprecate `:file_name` option set to string

Setting the upload file name to a fixed string is not quite useful from my opinion, therefore we can deprecate it. If the user still wants to set the filename to a fixed string, he can pass the lambda function, that always returns a string:

class Product
  mount_base64_uploader :image, SomeUploader, file_name: -> (_) { 'image' }
end

So for the next minor release we will just print out a deprecation warning in case the user is setting the file_name to a string, with a clear explanation that a lambda function should be used instead.

This way we can remove the extra conditional from the code.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.