Saving Base64 String in Rails
I want to save an image as a base64 string as part of开发者_运维技巧 a model in Rails.
Does anyone have advice for the migration file?
I assume that simply setting a type of String would not be suitable, given that the size of the string is often large e.g. > 2MB.You could use either text
or binary
instead of string
in your migration if you want to overcome the size limitation.
http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#method-i-column
The API documentation gives this example:
td.column(:picture, :binary, :limit => 2.megabytes)
# => picture BLOB(2097152)
The maximum size of TEXT
or BLOB
(binary) columns depends on your RDBMS (e.g. MySQL, PostgreSQL), available memory, and certain configuration settings. For instance, in MySQL, you should have a look at the max_allowed_packet
option, which you can set to anything up to 1 GB.
Regarding storage with Paperclip:
Paperclip doesn't allow database storage out of the box, so you have to write some custom code for that. Google gives me this:
http://patshaughnessy.net/2009/5/29/paperclip-sample-app-part-3-saving-file-attachments-in-a-database-blob-column
It's outdated though, so I'm not sure if it's helpful.
More importantly:
Note that storing files in database is generally not recommended which is why Paperclip doesn't support it. Some reasons it's a bad idea:
When images are stored in DB, every image request requires a call to your Rails app and the database, which has a massive negative effect on performance. If you store images as files or on Amazon S3, your app will scale much better.
Your database becomes large very quickly, which makes it harder to backup your data.
Since different RDBMS have different rules for column size, column types, etc., migrating large columns to a different database (e.g. from MySQL to PostgreSQL) may involve difficulties.
So I hope you have a good reason to do it anyway.
精彩评论