问题描述
我正在使用 Rails API 后端创建一个 React 应用程序。
我的组织模型有一个表单组件。
我需要帮助将文件/图像从前端正确存储到后端
在我开始使用 Active Storage 并添加将图像上传到表单的选项之前,我能够成功地为我的组织模型提交表单。所以这让我相信这是一个与 Active Storage 相关的孤立事件
- 在我的后端 我正在使用 Active Storage 并为我的组织模型设置了“has_many_attached :images”
组织模型
class Org < ApplicationRecord
has_many_attached :images
组织控制器
def create
org = Org.create(org_params)
if org.valid?
render json: { org: OrgSerializer.new(org) },status: :created
else
render json: { error: 'Failed to create org' },status: :not_acceptable
end
byebug
end
(甚至没有打我的再见)
组织参数
def org_params
params.require(:org).permit(...,:images=[])
end
不确定参数是“:images=[]”还是“images: []”
组织序列化程序
attributes ...,:images
def images
rails_blob_path(object.images,only_path: true) if object.images.attached?
end
- 在我的前端,我使用 React 类表单组件并将信息存储在状态中
状态
state = {
...,images: [],
表单输入
<label><strong>Add Organization Image: </strong></label>
<input
accept="image/*"
multiple={true}
type="file"
name='images'
onChange={this.onFileChange}
/>
onFileChange = (e) => {
this.setState({
[e.target.name]: e.target.files[0]
})
}
表单提交功能
handleOnSubmit = (e) => {
e.preventDefault()
const data = new FormData()
Object.keys(this.state).forEach((key,value) => {
return data.append(key,this.state[key])
})
const reqObj = {
method: 'POST',headers: {
//Take this out
},body: data
}
fetch("http://localhost:3001/api/v1/orgs",reqObj)
.then(newOrg => {
this.props.addOrg(newOrg)
this.props.history.push('/organizations')
})
}
如前所述,当我提交此表单时,我什至没有点击我的错误,因此我可以检查,而是在我的终端中收到以下内容:
Started POST "/api/v1/orgs" for ::1 at 2020-12-31 22:13:57 -0600
Processing by Api::V1::OrgsController#create as */*
Parameters: {...,"images"=>#<Actiondispatch::Http::UploadedFile:0x00007f99f2d66300 @tempfile=#<Tempfile:/var/folders/wq/_w197c7s5ns8wzw8l1wjf_k80000gn/T/RackMultipart20201231-6328-3buku3.jpg>,@original_filename="image3.jpg",@content_type="image/jpeg",@headers="Content-disposition: form-data; name=\"images\"; filename=\"image3.jpg\"\r\nContent-Type: image/jpeg\r\n">,Completed 400 Bad Request in 0ms (ActiveRecord: 0.0ms | Allocations: 121)
ActionController::ParameterMissing (param is missing or the value is empty: org):
app/controllers/api/v1/orgs_controller.rb:46:in `org_params'
app/controllers/api/v1/orgs_controller.rb:16:in `create'
我将不胜感激任何输入、反馈或帮助...
谢谢!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)