Source:  Twitter logo

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.

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.

19 users liked answer #0dislike answer #019
Ruslan Korkin profile pic
Ruslan Korkin

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>)
}
2 users liked answer #1dislike answer #12
egorchik profile pic
egorchik

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));
1 users liked answer #2dislike answer #21
Ahmed Mohammed Ahmed Ali profile pic
Ahmed Mohammed Ahmed Ali

If you need to send a request with more attributes than the image use:

document.getElementById('inputPhoto').addEventListener('change', (e) => {  
  let 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);
  });
});

Remember that all attributes should be appended BEFORE the image

0 users liked answer #3dislike answer #30
Nico Serrano profile pic
Nico Serrano

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).