【问题标题】:Upload to Rails Active Storage Using Javascript使用 Javascript 上传到 Rails 活动存储
【发布时间】:2020-04-09 23:03:21
【问题描述】:

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

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

顺便说一句,setFile 只是将“文件”设置为该对象。我正在使用反应。

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)
}

【问题讨论】:

    标签: javascript ruby-on-rails ruby rails-activestorage


    【解决方案1】:

    如果你使用 Active storage,请使用他们的 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
      }
    }
    
    
    

    link here

    【讨论】:

      猜你喜欢
      • 2020-11-10
      • 2019-03-12
      • 2020-10-18
      • 2020-09-07
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多