1

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

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

我想在 fetch 中传递我的参数。在我的情况下,参数是参数。我想将这些参数与我的图像一起发送到服务器。请帮忙。

更新

这是我使用 alert(JSON.stringify(response));

4

2 回答 2

2

您可以使用附加传递参数

参考链接:如何使用 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);
于 2019-01-15T11:09:31.863 回答
0

FormData不能采用字符串化的 JSON,但您可以遍历对象,将值附加到表单。像这样:

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);
      });    
  }
于 2019-01-15T10:52:17.313 回答