简体   繁体   English

在 Rails 中保存 Base64 字符串

[英]Saving Base64 String in Rails

I want to save an image as a base64 string as part of a model in Rails.我想将图像保存为 base64 字符串作为 Rails 中 model 的一部分。

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 eg > 2MB.我假设简单地设置一种 String 类型是不合适的,因为字符串的大小通常很大,例如 > 2MB。

You could use either text or binary instead of string in your migration if you want to overcome the size limitation.如果您想克服大小限制,可以在迁移中使用textbinary而不是string

http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#method-i-column http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#method-i-column

The API documentation gives this example: API 文档给出了这个例子:

td.column(:picture, :binary, :limit => 2.megabytes)
# => picture BLOB(2097152)

The maximum size of TEXT or BLOB (binary) columns depends on your RDBMS (eg MySQL, PostgreSQL), available memory, and certain configuration settings. TEXTBLOB (二进制)列的最大大小取决于您的 RDBMS(例如 MySQL、PostgreSQL)、可用的 memory 和某些配置设置。 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.例如,在 MySQL 中,您应该查看max_allowed_packet cket 选项,您可以将其设置为最大 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. Paperclip 不允许开箱即用的数据库存储,因此您必须为此编写一些自定义代码。 Google gives me this:谷歌给了我这个:

http://patshaughnessy.net/2009/5/29/paperclip-sample-app-part-3-saving-file-attachments-in-a-database-blob-column 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.请注意,通常不建议将文件存储在数据库中,这就是 Paperclip 不支持它的原因。 Some reasons it's a bad idea:这是一个坏主意的一些原因:

  1. 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.当图像存储在数据库中时,每个图像请求都需要调用 Rails 应用程序数据库,这会对性能产生巨大的负面影响。 If you store images as files or on Amazon S3, your app will scale much better.如果您将图像存储为文件或存储在 Amazon S3 上,您的应用程序的扩展性会更好。

  2. Your database becomes large very quickly, which makes it harder to backup your data.您的数据库很快就会变大,这使得备份数据变得更加困难。

  3. Since different RDBMS have different rules for column size, column types, etc., migrating large columns to a different database (eg from MySQL to PostgreSQL) may involve difficulties.由于不同的 RDBMS 对列大小、列类型等有不同的规则,将大列迁移到不同的数据库(例如从 MySQL 到 PostgreSQL)可能会遇到困难。

So I hope you have a good reason to do it anyway.所以我希望你有充分的理由去做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM