我刚刚学习 React 并创建了一个图库应用程序,但我在将图片发布到 API 时遇到问题。问题是,当我单击按钮
ADD
时,console.log 中没有任何反应,我得到一个 error 500
。
这是我的带有发布请求的组件:
class AddPhoto extends Component {
constructor(props) {
super(props);
this.state = {
modal: false,
images: [],
isLoading: false,
error: null,
};
this.toggle = this.toggle.bind(this);
this.handleClick = this.handleClick.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
toggle() {
this.setState({
modal: !this.state.modal
});
}
handleClick(event) {
event.preventDefault();
this.setState({
modal: !this.state.modal
});
}
handleSubmit(event){
event.preventDefault();
this.setState({ isLoading: true });
let path = this.props.path;
fetch(`http://.../gallery/${path}`, {
method: 'POST',
headers: {'Content-Type':'multipart/form-data'},
body: new FormData(document.getElementById('addPhoto'))
})
.then((response) => response.json())
.then((data)=>{
this.setState({images: data.images, isLoading: false});
this.props.updateImages(data.images);
})
.catch(error => this.setState({ error, isLoading: false}));
}
render() {
return (
<Card className="add">
<div className="link" onClick={this.toggle}>
<CardBody>
<CardTitle>Add picture</CardTitle>
</CardBody>
</div>
<Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}>
<div className="modal-header">
...
</div>
<ModalBody>
<form className="addPhotoForm" id="addPhoto" onSubmit={this.handleSubmit}>
<input type="file" required />
<Button color="success" type="Submit">Add</Button>
</form>
</ModalBody>
</Modal>
</Card>
);
}
}
你知道我做错了什么吗?为什么不起作用,为什么我收到错误 500?
谢谢你帮助我。
根据此https://muffinman.io/uploading-files-using-fetch-multipart-form-data它以不同的方式工作,至少对我来说它也有效。
const fileInput = document.querySelector('#your-file-input') ;
const formData = new FormData();
formData.append('file', fileInput.files[0]);
const options = {
method: 'POST',
body: formData,
// If you add this, upload won't work
// headers: {
// 'Content-Type': 'multipart/form-data',
// }
};
fetch('your-upload-url', options);
您应该删除
'Content-Type': 'multipart/form-data'
,它就开始工作了。
这是我的上传组件的一部分。 看看我是怎么做的,如果需要的话,你可以用上传按钮修改它。
addFile(event) {
const formData = new FormData();
formData.append("file", event.target.files[0]);
formData.append('name', 'some value user types');
formData.append('description', 'some value user types');
console.log(event.target.files[0]);
fetch(`http://.../gallery/${path}`, {
method: 'POST',
headers: {'Content-Type': 'multipart/form-data'},
body: {event.target.files[0]}
})
.then((response) => response.json())
.then((data) => {
this.setState({images: data.images, isLoading: false});
this.props.updateImages(data.images);
})
.catch(error => this.setState({error, isLoading: false}));
}
render() {
return (
<div>
<form encType="multipart/form-data" action="">
<input id="id-for-upload-file" onChange={this.addFile.bind(this)} type="file"/>
</form>
</div>)
}
这对我来说效果很好,试试吧:
var myHeaders = new Headers();
myHeaders.append("Accept", "application/json");
myHeaders.append("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJh");
var formdata = new FormData();
formdata.append("image", fileInput.files[0], "Your_iamge_URL");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: formdata,
redirect: 'follow'
};
fetch("YOUR_API_ToCall", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
如果您需要发送比图像更多属性的请求,请使用:
document.getElementById('inputPhoto').addEventListener('change', (e) => {
const data = new FormData();
const image = e.target.files[0];
data.append('id', 'sendIDHere');
data.append('name', 'sendNameHere');
data.append('image', image);
fetch('/apiToReceiveImage', {
method: 'POST',
body: data
}).then(async (_res) => {
const result = await _res.json();
console.log(result);
});
});
请记住,所有属性都应附加在图像之前