尝试将带有头像/图像的对象从React发布/放置到Rails Direct Upload

时间:2019-04-02 20:25:16

标签: ruby-on-rails reactjs blob rails-activestorage

我是React和Rails的新手。我将ActiveStorage和AWS S3和Direct_Upload都读入了Rails。在React中,当使用'avatar'或带有and'image'的帖子创建新用户或更新用户时,我不确定如何在Fetch请求中实现此功能。我听说过FormData,但不清楚“ user /'post”的属性如何将其与附加的“头像”或“图像”一起传递到后端。

这是我的UserSighting型号,在导轨上:

class User < ApplicationRecord
    include Rails.application.routes.url_helpers

    has_secure_password
    has_one_attached :avatar

    has_many :sightings
    has_many :animals, through: :sightings
    has_many :comments, :as => :commentable, dependent: :destroy


  def avatar_filename
    self.avatar.filename.to_s if self.avatar.attached?
  end

  def avatar_attached?
    self.avatar.attached?
  end



  validates :username, uniqueness: true

  def attachment_url
    if self.attachment.attached?
      Rails.application.routes.url_helpers.rails_blob_url(self.attachement, only_path: false)
    else
      nil
    end
  end

end
class Sighting < ApplicationRecord

  has_one_attached :image

  belongs_to :user
  belongs_to :animal
  has_many :comments, :as => :commentable, dependent: :destroy

  def image_filename
    self.image.filename.to_s if self.image.attached?
  end

  def image_attached?
    self.image.attached?
  end


end

并且我试图在React中进行这样的常规Fetch请求:


signup = (name, username, password, passwordConfirmation) => {
    if (password === passwordConfirmation) {
      fetch('http://localhost:9000/api/v1/users', {
        method: "POST",
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify({
          name: name,
          username: username,
          password: password
        })
      })
      .then(res => res.json())
      .then((response) => {
        if (response.errors) {
          alert(response.errors)
        } else {
          localStorage.setItem("token", response.token) // "jwt" can be any name
          this.setState({
            currentUser: response.user
          })
          this.props.history.push(`/login`)
        }
      })
    } else {
        alert("Passwords do not match!!")
    };
  };





How do I send avatar/image uploaded by user?

0 个答案:

没有答案