如何在Sinatra中使用CarrierWave显示图像

问题描述 投票:0回答:1

我在CarrierWave上苦苦挣扎,所以我做了一个小程序,看我能否做得到:

require 'sinatra'
require 'dm-core'
require 'dm-migrations'
require 'carrierwave/datamapper'

class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
end

DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/photogallery.sqlite3")

class Image
  include DataMapper::Resource

  property :id, Serial
  property :title, Text

  mount_uploader :image, ImageUploader
end

DataMapper.finalize
DataMapper.auto_migrate!

get "/" do
    @images = Image.all
    erb :index
end

post "/" do
    image = Image.new(:title => params[:title])
    image.image = params[:image]
    image.save

    redirect "/"    
end

__END__

@@ index
<% @images.each do |image| %>
    <p>
        <%= image.title %>
    </p>
    <a href="<%= image.image.url %>">
        <img src="<%= image.image.url %>">
    </a>
<% end %>

<form action="/" method="post">
    <label for="title">Title</label>
    <input type="text" name="title"><br>

    <label for="image">Image</label>
    <input type="file" name="image"><br>

    <input type="submit" value="Save">
</form>

当从计算机上载图像时,似乎无法显示图像。好像图像没有保存在任何地方,因此无法检索它们。

定位标记正确引用了图像应在的位置,但没有图像。

我在做什么错?

sinatra carrierwave datamapper
1个回答
0
投票

为@MrMos转换为answer ...

没关系,我发现了。我改为这样做:

require 'sinatra'
require 'dm-core'
require 'dm-migrations'
require 'carrierwave/datamapper'

DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/development.db")

class ImageUploader < CarrierWave::Uploader::Base
    storage :file

    def store_dir
        'images'
    end
end

class Image
    include DataMapper::Resource

    property :id, Serial
    property :title, Text

    mount_uploader :file, ImageUploader
end

DataMapper.finalize
DataMapper.auto_migrate!

get '/' do
    @images = Image.all
    erb :index
end

post '/' do
    Image.create(params[:image])
    redirect to('/')
end

__END__

@@ index
<!DOCTYPE html>
<html>
    <body>
        <form action="/" method="post" enctype="multipart/form-data"></div>
            <input type="text" name="image[title]" />
            <input type="file" name="image[file]" />
            <input type="submit" name="submit" value="Upload" />
        </form>
        <% @images.each do |image| %>
            <p><%= image.title %></p>
            <img src="/images/<%= images.file_identifier %>" />
        <% end %>
    </body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.