【问题标题】:js frontend fetch() post to rails backend filepath to file errorjs前端fetch()发布到rails后端文件路径到文件错误
【发布时间】:2020-03-11 20:03:36
【问题描述】:

我正在向 Rails 端点发出 javascript fetch() 发布请求。我正在使用 Active Storage 从本地计算机保存图片。浏览器不允许完整的文件路径通过。在带有 erb 的 rails 前端中,我可以使用图片并在 rails 视图中查看它。转到 JavaScript 前端并发布到 rails API 并不容易。我通过调试器和 binding.pry 知道代码中发生了什么。在 js 方面,文件路径被假路径混淆。因此,当我碰到后端的rails时,我就明白了。我正在使用活动存储 gem,在我的模型中我有一个 has_one_attached :file

前端

index.html <input type="file" id="myfile" name="myfile">

     //this will hit the endpoint
        fetch(BASE_URL + "/" + "pokemons/test", {
            method: 'post',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },

            body: JSON.stringify(obj)
        }).then( response => response.json()
    ) 

后端

#=>model.rb 
class Pokemon < ApplicationRecord 
  has_one_attached :file 
#=> backend rails terminal in pry 

    {"nickname"=>"first_try", "species"=>"fictional", "trainer_id"=>1, "file"=>"C:\\fakepath\\WIN_20200205_00_06_57_Pro.jpg", "controller"=>"pokemons", "action"=>"test", "pokemon"=>{"species"=>"fictional", "nickname"=>"first_try", "trainer_id"=>1}} 

terminal_errors: 

ActiveSupport::MessageVerifier::InvalidSignature (ActiveSupport::MessageVerifier::InvalidSignature):

`

【问题讨论】:

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


    【解决方案1】:

    这是我的问题的一半答案。它以 html 和浏览器尝试屏蔽我的计算机中的文件开始,并以适当的 html 输入表单结束以接受和上传文件。 proper form

    现在,我的 html 表单已针对此特定目的进行了更新,即使对我的 rails 端点采取了适当的操作,我也可以将图像文件保存到 Active Storage 中

    这是我的html

      <div>
        <label for="file">Choose a file</label>
        <input type="file" id="file" name="file"> 
        <input type="text" id="nickname" name="nickname"> 
        <input type="text" id="species" name="species"> 
        <input type="number" id="trainer_id" name="trainer_id">
      </div>
      <div>
        <button id="test">Send the file</button>
      </div>
    </form>``` 
    
    Now that my html is handling the posting action to my rails API I just need a way to open the file and view it. 
    
    

    【讨论】:

      猜你喜欢
      • 2022-07-03
      • 1970-01-01
      • 2021-01-04
      • 1970-01-01
      • 2022-11-20
      • 2021-02-06
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      相关资源
      最近更新 更多