使用对活动存储的反应上传图像 rails

Upload image using react to active storage rails

我可以通过postman成功上传图片到amazon s3 bucket。我正在使用 active storage 概念。当我使用 React 构建我的前端时,我将如何存储我的图像以响应状态并将其发送到参数中以 rails 后端。

我使用一个名为 react-dropzone 的包来去除状态存储文件以及从 React 上传图像到 API 的一些繁琐部分。

这里有一个非常概念性的例子:

import React, { Component } from "react";
import PropTypes from "prop-types";
import Dropzone from "react-dropzone";

export default class UploadImage extends Component {
  state = {
    files: []
  };

  onDrop = (files) => {
    // Get existing files from state
    // (or just the empty array if there are no files in state)
    var currentFiles = this.state.files;

    // Push file(s) from function parameters to `currentFiles` array
    const [newFiles] = files;
    currentFiles.push(newFiles);

    // Assign files dropped into component into state
    this.setState({
     files: currentFiles
    });

    // Attempt to upload the files.
    // If you want to upload after a button click, move the code
    // below to its own function and have it run after button click.
    if (files.length) {
      let formPayLoad = new FormData();

      // I'm using "avatar" here for the attribute name of the model that
      // will store the image. Change the first parameter of the 'append' function
      // below to be the name of the attribute name that fits your Rails model.
      formPayLoad.append("avatar", files[files.length - 1]);

      // Pass the data to your own defined upload function
      // that makes the call to your API. Make sure you put the
      // formPayLoad in the body of the request.
      this.props.upload(formPayLoad);
    }
  }

  render() {
    return (
      <div className="upload-image-component">
        <Dropzone
          onDrop={this.onDrop}
          multiple={true}
        >
          <p>Text that says to upload file.</p>
        </Dropzone>
      </div>
    );
  }
}

然后让您的 Rails 控制器接受我们在上面 'onDrop' 的 'append' 函数中定义的属性。在我的示例中,我使用 "avatar"。另一个非常概念性的例子:

class UserController < ApiController

  # your actions

  private

  def user_params
    params.permit(
      # all your other params
      :avatar
    )
  end

end