如何使用 fetch 发布图像?

IT技术 javascript reactjs post fetch-api
2021-04-11 05:39:56

我刚刚学习 react 并创建了一个图库应用程序,但是我在将图片发布到 API 时遇到了问题。问题是,当我点击按钮时ADD,在 console.log 中什么也没发生,我得到了一个error 500.

这是我的 post 请求组件:

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?

谢谢你帮助我。

3个回答

根据这个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) {
    var 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>)
}
看起来很有趣。console.log(event.target.files[0]); 之后 在控制台中,我看到了我想发布的文件。但不幸的是我不知道如何放入 fetch 请求。
2021-05-27 05:39:56
您创建了一个“var formData...”,但您没有使用 i。
2021-06-11 05:39:56

这对我来说很好用,试试吧:

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));