Rails4:如何将carrierwave上传的图像存储在私人文件夹中?

时间:2014-09-30 13:36:49

标签: ruby-on-rails ruby-on-rails-4 carrierwave

我已在公共文件夹下载了带有carrierwave的图像。 出于安全原因,我打算将文件夹更改为根目录。

Althogh我提到帖子How to: Secure Upload并创建了carrierwave.rb,我不知道如何编写carrierwave上传的路径。

如何在私人文件夹下显示图像?

image_uploader.rb

class ImageUploaader < CarrierWave::Uploader::Base

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

end

我创建了\ config \ initializers \ carrierwave.rb

CarrierWave.configure do |config|
  config.permissions = 0600
  config.directory_permissions = 0700
  config.root = Rails.root
end

我还创建了images_controller.rb

class ImagesController < ApplicationController
    #I tried some, but doesn't work
end

我使用以下视图显示图像 \ views \ articles \ _article.html.erb

<% article.photos.each do |photo| %>
  <%= image_tag(photo.image_url(:thumb).to_s, class: :thumb) if photo.image? %>
<% end %>

如果您可以在routes.rbimages_controller.rb_article.html.erb中指定代码,我们将不胜感激。

2 个答案:

答案 0 :(得分:0)

我正在通过Rails 4 In Action,我们有类似的需求。在那本书中,他们让我们在app根目录下创建一个名为“files”的文件夹。

然后我们更改了上传器中的行:

uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}

files/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}

现在,在那本书中,文件被删除到files目录。然后使用CanCanCan之类的内容设置权限或自己编写权限。这似乎是它。我想。

答案 1 :(得分:0)

这是一个古老的问题,也许它会像帮助我一样帮助别人。 我认为您误解了参考资料中的解释: 添加此路线:

match "/uploads/photos/:id/:basename.:extension", controller: "photo", action: "send_img", via: :get

因此,每个类似/uploads/photos/1/best_ever_img.png的URL请求都将被“重定向”到photos控制器中的send_img操作

在您采取行动时,

类照片 mount_uploader:image,ImageUploaader

def send_img
    id = params[:id]
    basename = params[:basename]
    extension = params[:extension]
    type = params[:type]
    # if you have a different environment in your dev and production, you can add each unique route
    if Rails.env.development?
        # The route to your project folder
        # My dev server is on windows Linux shell so the route is like this, you may use other development environment so just update the route
        base_url = "/mnt/c/Users/YOUR_USER_NAME/Desktop/Sites/"
    else
        base_url = "/home/deploy"
    end
    # Replace the `YOUR_PROJECT_FOLDER` with name of yours
    path = "#{base_url}/YOUR_PROJECT_FOLDER/uploads/photos/image/#{id}/#{basename}.#{extension}"
    send_file path, x_sendfile: true
end

在您看来,像这样加载图像:

<%= image_tag "uploads/photos/#{photo.id}/#{File.basename(photo.image.url)}" %>