请教大家:我是在本地用 rails 搭建网站,现在想在本地能把图片上传到又拍云,网站一些代码如下。但是上传图片后,跳转到show.html.erb
,图片的地址是:http://sssss-imgs.test.upcdn.net/img/img_name/00502fb437cb5ed9032f9393600578d8.png!320
,图片打不开,好像图片没有上传到又拍云的服务器。请问我这是哪里出现了错误?请大家指导,非常感谢!!
1. 部分 Gemfile
:
gem 'carrierwave', '~> 1.2', '>= 1.2.2'
gem 'carrierwave-upyun', '~> 0.2.2'
gem 'mini_magick'
2. config/initializers/carrierwave.rb
: (这个是手动新增加的)
require "carrierwave"
require "carrierwave/validations/active_model"
CarrierWave.configure do |config|
config.storage = :upyun
config.remove_previously_stored_files_after_update = false
config.upyun_username = "sssss"
config.upyun_password = "ssssss123"
config.upyun_bucket = "sssss-imgs"
config.upyun_bucket_domain = "http://sssss-imgs.test.upcdn.net"
config.upyun_api_host = "http://v0.api.upyun.com"
end
3. 基本上传组件 BaseUploader
:
IMAGE_UPLOADER_ALLOW_IMAGE_VERSION_NAMES = %(320 640 800)
class BaseUploader < CarrierWave::Uploader::Base
storage :upyun
def store_dir
"#{model.class.to_s.underscore}/#{mounted_as}"
end
def extension_white_list
%w[jpg jpeg gif png svg]
end
def url(version_name = "")
@url ||= super({})
version_name = version_name.to_s
return @url if version_name.blank?
if not version_name.in?(IMAGE_UPLOADER_ALLOW_IMAGE_VERSION_NAMES)
# To protected version name using, when it not defined, this will be give an error message in development environment
raise "ImageUploader version_name:#{version_name} not allow."
end
[@url,version_name].join("!")
end
end
4. 图片上传组件 ImgUploader
:
class ImageUploader < BaseUploader
def filename
if original_filename
@name||=Digest::MD5.hexdigest(File.dirname(current_path))
"#{@name}.#{file.extension}"
end
end
end
5. models img.rb
:
class Img < ActiveRecord::Base
mount_uploader :img_name, ImageUploader
end
6. imgs_controller.rb
:
class ImgsController < ApplicationController
def index
@imgs = Img.all
end
def show
@img = Img.find(params[:id])
end
def new
@img = Img.new
end
def create
@img = Img.new(img_params)
@img.save
redirect_to @img
end
def destroy
@img.destroy
render :index
end
private
def img_params
params.require(:img).permit!
end
end
7. 上传图片和图片展示 :
## new.html.erb
<%= form_for @img do |f| %>
<%= f.file_field :img_name %>
<%= f.submit "上传" %>
<% end %>
## show.html.erb
<%= image_tag(@img.img_name.url("320")) %>
8. img 的 migration:
class CreateImgs < ActiveRecord::Migration[5.2]
def change
create_table :imgs do |t|
t.string :img_name
t.timestamps null: false
end
end
end