1

This is the code with I'm trying to send my image to server.

 postData = async () => {   
        var location = await AsyncStorage.getItem('location');        
        var path = await AsyncStorage.getItem('path');
        var post_type = await AsyncStorage.getItem('post_type');    
        var userId = await AsyncStorage.getItem('userID');

    const formData = new FormData();

//I want to pass params in fetch but I don't know how to.     

       var params = JSON.stringify({ 
            "user": userId,
            "description": this.state.description,
            "location": location,
            "post_type": post_type,
          });

    const uriPart = path.split('.');
    const fileExtension = uriPart[uriPart.length - 1];

    formData.append('photo', {
        uri: path,
        name: `photo.${fileExtension}`,
        type: `image/${fileExtension}`,
    });

    fetch(strings.baseUri+"addPosts",{
        method: 'POST',
        headers: {
            'Content-Type': 'multipart/form-data',
          },
        body: formData,
      })
      .then((response) => response.json())
      .then((responseJson) => {

       alert(responseJson); // This gives me error JSON Parse error: Unexpected EOF

      })
      .catch((error) => {
          console.error(error);
      });    
  }

I want to pass my parameters in fetch. The parameters are params in my case. I want to send these parameters along with my image to server. Please help.

UPDATE

this is when I used alert(JSON.stringify(response));

Shubham Bisht
  • 577
  • 2
  • 26
  • 51

2 Answers2

2

You can pass parameter with append

reference link: How do I post form data with fetch api?

const formData = new FormData();

formData.append('photo', {
  uri: path,
  name: `photo.${fileExtension}`,
  type: `image/${fileExtension}`,
});

formData.append('user', userId);
formData.append('description', description);
formData.append('location', location);
formData.append('post_type', post_type);
IftekharDani
  • 3,619
  • 1
  • 16
  • 21
0

FormData cannot take stringified JSON, but you can iterate over the object, appending values to the form. Like this:

var params = { 
            "user": userId,
            "description": this.state.description,
            "location": location,
            "post_type": post_type,
          };

    const uriPart = path.split('.');
    const fileExtension = uriPart[uriPart.length - 1];

    formData.append('photo', {
        uri: path,
        name: `photo.${fileExtension}`,
        type: `image/${fileExtension}`,
    });

    Object.keys(params).forEach(key => formData.append(key, params[key]));

    fetch(strings.baseUri+"addPosts",{
        method: 'POST',
        headers: {
            'Content-Type': 'multipart/form-data',
          },
        body: formData,
      })
      .then((response) => response.json())
      .then((responseJson) => {

       alert(responseJson); // This gives me error JSON Parse error: Unexpected EOF

      })
      .catch((error) => {
          console.error(error);
      });    
  }
Mikhail Litvinov
  • 452
  • 2
  • 10