我使用Rails 5在本地主机上构建网站,现在我想将图片上传到upyun服务器。但是使用下面的代码,我只得到图片网址:http://sssss-imgs.test.upcdn.net/img/img_name/00502fb437cb5ed9032f9393600578d8.png!320
,而没有将图片上传到upyun服务器,因此无法打开图片,我的代码出了什么问题,有人帮忙吗?非常感谢!!
1。我的一些Gemfiles
gem 'carrierwave', '~> 1.2', '>= 1.2.2'
gem 'carrierwave-upyun', '~> 0.2.2'
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)
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。我的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。我的img new.html.erb
和show.html.erb
## new.html.erb
<%= form_for @img do |f| %>
<%= f.file_field :img_name %>
<%= f.submit "upload" %>
<% end %>
## show.html.erb
<%= image_tag(@img.img_name.url("320")) %>
8。我对img的迁移
class CreateImgs < ActiveRecord::Migration[5.2]
def change
create_table :imgs do |t|
t.string :img_name
t.timestamps null: false
end
end
end
非常感谢您的回答,这个问题困扰了我好几天了。