如何在获取中传递POST参数以在React Native中将图像上传到服务器?

时间:2019-01-15 10:43:07

标签: reactjs react-native react-native-camera react-native-fetch-blob react-native-fs

这是我尝试将图像发送到服务器的代码。

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

我想在获取中传递参数。在我的情况下,参数是参数。我想将这些参数以及我的图像发送到服务器。请帮忙。

更新

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

2 个答案:

答案 0 :(得分:1)

  

您可以通过append传递参数

参考链接: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);

答案 1 :(得分:-1)

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