【发布时间】: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