使用Javascript上传到Rails活动存储

使用Javascript上传到Rails活动存储,javascript,ruby-on-rails,ruby,rails-activestorage,Javascript,Ruby On Rails,Ruby,Rails Activestorage,我正在尝试将映像上载到Rails后端的活动存储中。我目前的后端设置是正确的,但我很难理解FormData。这是我的 on change函数正在侦听“file”类型的输入中的更改。当我将照片添加到输入中时,我可以从e.target获取信息。。。但是我不知道在这里添加什么作为URI。这里的e.target.value是一个受保护的uri。所以我对这应该如何工作感到困惑: 顺便说一下,setFile只是将“file”设置为该对象。我在用react const onChange = (e) =>

我正在尝试将映像上载到Rails后端的活动存储中。我目前的后端设置是正确的,但我很难理解FormData。这是我的

on change函数正在侦听“file”类型的输入中的更改。当我将照片添加到输入中时,我可以从e.target获取信息。。。但是我不知道在这里添加什么作为URI。这里的e.target.value是一个受保护的uri。所以我对这应该如何工作感到困惑:

顺便说一下,setFile只是将“file”设置为该对象。我在用react

const onChange = (e) => {
    console.log(e.target.files)
    setFile({
        uri: e.target.value,
        name: e.target.files[0].name,
        type: e.target.files[0].type
    })
}

const onSubmit = () => {
    console.log(file)

    let imageURI = file.uri
    let formdata = new FormData();

    formdata.append("image", { uri: imageURI, name: `${file.name}`, type: `${file.type}` })
    formdata.append("image", file)

    requests.postImageToCurriculum(66, formdata)
}

如果您使用的是活动存储,请使用他们的js包



import { DirectUpload } from "@rails/activestorage"

class Uploader {
  constructor(file, url) {
    this.upload = new DirectUpload(this.file, this.url, this)
  }

  upload(file) {
    this.upload.create((error, blob) => {
      if (error) {
        // Handle the error
      } else {
        // Add an appropriately-named hidden input to the form
        // with a value of blob.signed_id
      }
    })
  }

  directUploadWillStoreFileWithXHR(request) {
    request.upload.addEventListener("progress",
      event => this.directUploadDidProgress(event))
  }

  directUploadDidProgress(event) {
    // Use event.loaded and event.total to update the progress bar
  }
}