如何发送图像在更改reactjs中的组件时抛出一个post-request

时间:2018-06-15 15:44:41

标签: reactjs http-post components

我正在使用reader.onload从计算机上传图像并将其保存在组件状态中。 然后我有一个链接按钮,在发送我的图像时渲染一个不同的组件抛出一个帖子请求。当我加载它时我会调度图像。它会显示图像,但是我会在帖子显示未定义之前控制日志。

class ByImage extends Component {
    state = {
        image : null
    }

    fileSelectedHandler = event => {

        if (event.target.files && event.target.files[0]) {

            let reader = new FileReader();

            reader.onload = () => {
                this.setState({image: reader.result});
            };

            reader.readAsDataURL(event.target.files[0]);
            console.log(event.target.files[0].name);
        }
    }

    fileUploadHandler = () => {

        const fd = new FormData();

        fd.append('image' + this.state.image, this.state.image.name);

        console.log("Image:" + this.state.image); // --> this.state.image == undefined

        let config = {
            headers: {
                'Content-Type': 'image/jpeg',
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "GET,HEAD,OPTIONS,POST,PUT"
            }
        } 
        axios
        .post(`${APIurl}`, fd, config)
        .then(res => {
            console.log(res);
        }).catch(err =>{
            console.log(err);
        });
    }

    render() {
        return (
            <div className="card-background has-text-centered has-border-radius">
                <h1>
                    Find By Image
                </h1>
                <p className="level-item has-text-centered has-margin20px">
                    <img className="has-border" src={ this.state.image ? this.state.image : imgIcon }/>
                </p>
                <a className="button is-link is-rounded">
                    <input 
                        className="file-input"
                        type="file"
                        accept=".jpg, .png, .jpeg"
                        onChange={this.fileSelectedHandler}
                    />
                    <span className="icon has-padding-right">
                        <i className="fa fa-upload"></i>
                    </span>
                    Choose Image to Upload
                </a> 
                <br/>
                <Link className="button is-link is-rounded has-margin-top10" to="/imageSearchResult" onClick={this.fileUploadHandler}>
                    <span className="icon has-padding-right">
                        <i className="fa fa-search "></i>
                    </span>
                    Search
                </Link> 
            </div>
        );
    }
}

0 个答案:

没有答案