代码之家  ›  专栏  ›  技术社区  ›  Anu

如何使用fetchinreact native上传文件和文本?

  •  0
  • Anu  · 技术社区  · 6 年前

    我正在尝试使用将文件上载到服务器 react-native-document-picker

    unhandled promise rejection unsupported BodyInit type

    代码的更新部分

     filepick = () => {
        DocumentPicker.show({
            filetype: [DocumentPickerUtil.images()],
        }, (error, res) => {
            if (error == null) {
                console.log(
                    res.uri,
                    res.type, // mime type
                    res.fileName,
                    res.fileSize
                );
                this.setState({
                    img_uri: res.uri,
                    img_type: res.type,
                    img_name: res.fileName
    
                })
            } else {
                Alert.alert('Message', 'File uploaded failed');
            }
        });
    };
    
    
     onPressSubmit() {
    
            const data = new FormData();
            data.append('file', { uri: this.state.img_uri, type: 
           this.state.img_type, name: this.state.img_name })
            data.append('comment', { text: this.state.text });
            AsyncStorage.getItem("userdetail").then(value => {
                fetch(GLOBAL.ASSN_URL +`${this.props.id}`, {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'multipart/form-data',
                        'Authorization': value
                    },
                    body: data
                }).then((response) => {
                    return response.text()
                }).then((responseJson) => {
                    var result = responseJson;
    
                    console.log(result);
    
                });
            })
        }
    

    函数 filepick()

    1 回复  |  直到 6 年前
        1
  •  0
  •   Umair Abid    6 年前
    body: ({
        file: this.state.file,
        comment: this.state.text
    })
    

    你为什么用括号把尸体包起来?移除它们可能会修复它。

    也看看这个, https://github.com/facebook/react-native/issues/6025 application/json

    body: JSON.stringify({
            file: this.state.file,
            comment: this.state.text
    })
    

    编辑

    2) 上载响应包含有关文件的信息

    4) 您需要用该实体保存文件

    你基本上不需要用你的实体再次上传整个文件,因为它已经上传到服务器上了,你所需要做的就是用实体保存文件的引用。它们是保存引用的两种方法

    只需将fileName或fileUrl保存在entity表中,然后将名称或url与entity一起存储,使其看起来像这样

    {
      id: 1,
      name: 'Cat',
      picture: // url or name of picture
    }
    

    2) 将上传的文件保存在不同的表中,然后将文件的id与实体一起保存,当您获取实体时,会得到相关的文件。但是,如果实体和文件之间的关系是一对多的,因为在一个实体中可以有多个文件,那么您首先需要保存实体,然后参照实体上载文件。这样你的实体就会变成这样

    {
      id: 1,
      name: 'Cat',
      pictures: [{fileName: 'cat1'}, {fileName: 'cat2'}]
    }