我正在向rails端点发出javascript fetch((post请求。我正在使用活动存储从本地计算机保存图片。浏览器不允许完整的文件路径通过。在带有erb的rails前端,我可以使用图片并在rails视图中查看。进入JavaScript前端并发布到rails API并不容易。我知道调试器和binding.pry在代码中发生了什么。在js端,文件路径被伪路径混淆。因此,当我在后台遇到问题时,我会得到确切的答案。我使用的是活动存储宝石,在我的模型中,我有一个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):
`
这是我的问题的一半答案。它开始于html和浏览器试图屏蔽我电脑中的文件,结束于一个正确的html输入表单来接受和上传文件。正确形式
现在,我的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.