How to post image with fetch?

29,321

Solution 1

according to this https://muffinman.io/uploading-files-using-fetch-multipart-form-data it works in different way, at least for me it works as well.

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

You should remove the 'Content-Type': 'multipart/form-data' and it started to work.

Solution 2

This is part of my upload component. Look how i do it, you can modify it, with upload button, if you need.

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

Solution 3

This worked fine for me, just try it:

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));
Share:
29,321
Zoltan Kovacs
Author by

Zoltan Kovacs

Updated on December 26, 2020

Comments

  • Zoltan Kovacs
    Zoltan Kovacs over 3 years

    I just learning react and I create an gallery App, but I have problem with posting picture to API. The problem is that when I click on button ADD there's nothing happend just in console.log I get an error 500.

    Here is my component with post request:

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

    Do you have any idea what am I doing wrong, why is not working, why I get error 500?

    Thanks for helping me.

  • Zoltan Kovacs
    Zoltan Kovacs over 6 years
    it's look like interesting. After console.log(event.target.files[0]); in console i see the file what I want to post. But unfortunately I don't know how to put into fetch request.
  • Yrineu Rodrigues
    Yrineu Rodrigues about 4 years
    You create a 'var formData...' but you're not using i.