【发布时间】:2020-06-03 12:19:48
【问题描述】:
我一直在努力寻找上传图像并将其存储在数据库中的解决方案。
都试过了:Dropzone、react-dropzone、react-uploader 等等.....
BackEnd API 期望这样:
{
"course": {
"title": "Hic et velit sed.",
"subtitle": "Omnis quibusdam illum itaque.",
"description": "Et ullam ipsum. Illum dolor odit. Id veritatis ducimus.",
"end_date": "2020-02-01",
"attachment_attributes": {
"file": {
--- here the uploaded data file ---
}
}
}
}
我的组件现在只使用 1 个输入 type=file 来编写以加快测试速度。标题、副标题等 API 要求将被硬编码。
这里是组件:
import React, { Component } from 'react';
import api from '../../../../helpers/API';
class Uploader extends Component {
constructor(props) {
super(props);
this.state = {
selectedFile: null
}
}
onChangeHandler = event => {
this.setState({
selectedFile: event.target.files[0],
loaded: 0,
})
}
onClickHandler = () => {
** HARDCODED API REQUIREMENT**
const body = "course": {
"title": "Hic et velit sed.",
"subtitle": "Omnis quibusdam illum itaque.",
"description": "Et ullam ipsum. Illum dolor odit. Id veritatis ducimus.",
"end_date": "2020-02-01",
"attachment_attributes": {
"file": {
--- here the uploaded file data ---
}
}
}
** THIS SHOULD HANDLE THE UPLOADED FILE DATA FORMAT **
const data = new FormData()
data.append('file', this.state.selectedFile)
return api
.post("http://localhost:3000/api/v1/files", ??????). <— DATA or BODY?
.then(res => {
console.log(res.statusText)
})
.catch(res => console.log('error ==> ', res))
}
render() {
return (
<>
<div>
<label>Upload Your File </label>
<input
type="file"
multiple onChange={this.onChangeHandler}/>
</div>
<button type="button" className="btn btn-success btn-block" onClick={this.onClickHandler}>Upload</button>
</>
)
}
}
export default Uploader
问题
如果我在 API 调用中传递 DATA,上传的文件会很好地存储在 Browser > Network > Header > Data Form 部分中,作为文件:二进制
这很好。
但我需要将上传的文件作为我的 BODY 对象的一部分传递。所以,下面是我所做的,但它返回为空:
onClickHandler = () => {
const data = new FormData()
data.append('file', this.state.selectedFile)
const body = {
"course": {
"title": "Hic et velit sed.",
"subtitle": "Omnis quibusdam illum itaque.",
"description": "Et ullam ipsum. Illum dolor odit. Id veritatis ducimus.",
"end_date": "2020-02-01",
"attachment_attributes": {
"file": data <-- trying to pass the uploaded DataForm here
}
}
}
return api
.post("http://localhost:3000/api/v1/files", body)
.then(res => {
console.log(res.statusText)
})
.catch(res => console.log('error ==> ', res))
}
不幸的是,我得到了422 error,{"errors":{"attachment.file":["blank"]}}
非常感谢任何帮助。谢谢
鞠躬
【问题讨论】: