【问题标题】:How to post image with fetch?如何使用 fetch 发布图像?
【发布时间】:2018-06-25 07:47:44
【问题描述】:

我刚刚学习 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?

谢谢你帮助我。

【问题讨论】:

  • 这个错误比代码号更能提供信息 - 它说什么?
  • POST api.../gallery/test2 500(内部服务器错误)
  • 我的想法是文件未正确附加,但没有必要进行猜谜游戏。转到网络选项卡下的开发者控制台,检查服务器到底在尖叫什么。
  • 代码:500 描述:"内部服务器错误" 异常:"ValueError("多部分形式的无效边界:''" ,)" 名称:"INTERNAL_SERVER_ERROR"
  • 好吧,我是对的,服务器期望不同的格式(每个框架都不同)。在 lavarel 中对我有用的是做 body: new FormData(document.getElementById('addPhoto').files[0])

标签: javascript reactjs post fetch-api


【解决方案1】:

根据这个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' 并且它开始工作。

【讨论】:

    【解决方案2】:

    这是我的上传组件的一部分。 看看我是怎么做的,你可以修改它,如果你需要的话,用上传按钮。

    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 请求。
    • 你创建了一个 'var formData...' 但你没有使用 i。
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-10-21
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 2017-07-02
      • 1970-01-01
      • 2020-02-12
      • 2018-03-20
      相关资源
      最近更新 更多