Ruby on Rails保存圖像的方式是什麼?


我在iOS上進行開發,並且從PHP後端切換到Ruby on Rails。交換格式為JSON


在PHP中,接收數據,生成文件名,將該文件保存到磁盤以及使用映像在磁盤上的位置更新數據庫是相當標準的。對於Ruby on Rails來說是一樣的嗎?還是我不知道某些內置的ActiveRecord圖像功能?


What I've done in the past is use PaperClip with Amazon S3 and CloudFront CDN for faster delivery. PaperClip supports S3 storage very nicely out of the box: see their documentation for S3 storage configuration options.

  1. Set up a CloudFront distribution to forward image requests to your S3 bucket and other requests for static assets to your Ruby on Rails application (alternatively, you can upload those to S3 as well, but that's outside the scope of this question).
  2. CNAME a domain you control (such as to point to your CloudFront distribution.
  3. In the PaperClip configuration, set s3_host_alias: This will cause generated URLs to saved image resources to use your CloudFront distribution host.
  4. In your Ruby on Rails configuration, you can then do config.action_controller.asset_host = Ruby on Rails asset URLs will then also use your CloudFront distribution, for caching/faster delivery.

That's pretty sketchy, but it hopefully points you in the direction of some useful resources. Of course, that's just one solution, but it's one that has worked for me in a situation where I was dealing with hundreds of thousands of image attachments in the database.

(As a possible advanced step that may not be necessary or useful for your case, you can also set up multiple CNAMEs for your CloudFront distribution, such as and Both paperclip s3_host_alias and action_controller.asset_host can then take lambdas that will allow you to deterministically (based on the asset) generate URLs that use different hosts, for better parallelization if you're downloading a bunch of them on the same page, as browsers will limit the maximum simultaneous connections to the same host.)


I've tried several gems, but now I'm using FineUploader together with PaperClip

FineUploader handles a lot of the GUI for you, for example upload progress, drag-and-drop and multiple file uploads, and so on. I'm using PaperClip because I want to store the images on my servers instead of on S3.

What we normally do is look for a stable out-of-the-box configurable solution instead of recreating stuff from scratch. With PaperClip I store the images and with a StateMachine I do conversions on the images and put them into a category based on filename. I had the same question you had, and this was my best working solution, that's why I share it.