使用ActiveStorage进行文件上传和云上传

#必须更新到rails 5.2
rails active_storage:install #拷贝Blob这个model,使用多态的形式存储上传的文件名称等属性
rails db:migrate

#使用activestorage不用创建新的字段,但是在model中需要指明字段
class User < ApplicationRecord
  #user这个model中不必建立avatar和images这两个字段
  has_one_attached :avatar
  has_many_attached :images
end

使用minio进行云上传

brew install minio #安装minio
minio server storage #生成服务

#生成内容如下
Endpoint:  http://10.132.14.158:9000  http://192.168.0.104:9000  http://127.0.0.1:9000
AccessKey: 3ELS3ONCG9XVR2CNI1IP
SecretKey: h3/KXpVf0XUOfDiioyLKvhzwGj/w6GnvD1Ihynhg

#登录和访问照片
http://127.0.0.1:9000/minio

#config/storage.yml
amazon:
  service: S3
  access_key_id: 3ELS3ONCG9XVR2CNI1IP
  secret_access_key: h3/KXpVf0XUOfDiioyLKvhzwGj/w6GnvD1Ihynhg
  region: us-east-1
  bucket: jayzen  #需要登录http://127.0.0.1:9000/minio进行设置
  endpoint: http://192.168.0.104:9000
  force_path_style: true

需要使用的额外gem

gem 'mini_magick'
gem 'aws-sdk-s3', require: false

model使用关联Blob的多态方法,并介绍controller和view中的使用

#model
class User < ApplicationRecord
  has_one_attached :avatar
  has_many_attached :images
end

#controller
params.require(:user).permit(:first_name, :last_name, :avatar, images: [])

#view
#_new.html.erb
<div class="field">
    <%= form.label :avatar %>
    <%= form.file_field :avatar, direct_upload: true %>
  </div>

  <div class="field">
    <%= form.label :images %>
    <%= form.file_field :images, direct_upload: true, multiple: true %>
  </div>

#show.html.erb
#attached?  
<%= @user.avatar.attached? %>

#link content
<%= link_to url_for(@user.avatar), url_for(@user.avatar) %>

#variant
  <%= image_tag @user.avatar.variant(resize: "25x25") if @user.avatar.image? %>

#image?
<%= image_tag url_for(@user.avatar) if @user.avatar.image? %>

#images
<% @user.images.each do |image| %>
  <%= image_tag image.variant(resize: '50x50') if image.image? %>
<% end %>

#content_type
<%= @user.avatar.content_type %>

对上传文件显示进度条

#参考guides中的实例代码
direct_uploads.js
direct_uploads.css

source

minio

results matching ""

    No results matching ""