我在包含图像的 React 组件中有一个表单。该组件具有表单的关联状态,它是一个相当大且复杂的表单,具有许多长度不同的子元素嵌套数组,这就是我不想使用 FormData() 的原因。
state = {
recipe: {
title: "",
image: null,
ingredient_groups: [
{
title: "",
ingredients: [
{
name: "",
measurement_metric: "",
measurement_imperial: ""
}
]
}
]
}
使用输入字段的 onChange 处理程序更新状态,如下所示
let {recipe} = this.state;
recipe.image = event.target.files[0];
this.setState({recipe});
然后通过 axios post 请求发送,
let {recipe} = this.state;
axios.post('/api/v1/recipe', {recipe: recipe}).then((result) => {
console.log(result.status)
})
在 rails 中,我为允许的参数设置了一个参数方法
def recipe_params
params.require(:recipe).permit(:title,
:image,
{ingredient_groups: [
:id,
:title,
{ingredients: [
:id,
:name,
:measurement_metric,
:measurement_imperial
]}
]})
end
但是,当我尝试像这样将它保存到事件存储中时,recipe_params[:image] 得到的结果为 nil:
@recipe.image.attach(recipe_params[:image])
我在做什么可能吗?或者是通过帖子上的 FormData 对象传输此信息的唯一方法。我真的更希望通过纯 json 方法完成此操作。
最佳答案
使用 https://www.npmjs.com/package/object-to-formdata我能够成功地将我的 react 状态对象更改为 FormData 对象,然后将其发布到我的端点并且它按预期工作
关于ruby-on-rails - 使用 react 和 json 将图像上传到 rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64878590/