首页 > 解决方案 > 如何在具有其他属性 React-native 的 fetch 正文中将文件(docx,pdf)发送到服务器?

问题描述

我必须将带有简历的人的描述发送到服务器我有API但是当我用谷歌搜索这个问题时,只有获取文件的来源,但我必须发送带有名称的文件......所以我看到库文档选择器但是无法想象如何连接此提取。

有道具

constructor(props){
    super(props)
    this.state={
        token: {
            accessToken:""
        },
        nameCan: '',
        surename: '',
        experience: '',
        city: '',
        phone: '',
        email: '',
        file: {},
    }
}

有按钮的代码下载

_pickDoc = async() => {
    let result = await DocumentPicker.getDocumentAsync({});
    alert(result.uri);
    this.setState(this.state.file = result);
    console.log(result);
}

有 Fetch 的代码

async createCV(){
    let url = this.state.file.uri; //The url you received from the DocumentPicker


    const split = url.split('/');
    const name = split.pop();
    const inbox = split.pop();
    const realPath = `${RNFS.TemporaryDirectoryPath}${inbox}/${name}`;

    const uploadBegin = (response) => {
        const jobId = response.jobId;
        console.log('UPLOAD HAS BEGUN! JobId: ' + jobId);
    };

    const uploadProgress = (response) => {
        const percentage = Math.floor((response.totalBytesSent/response.totalBytesExpectedToSend) * 100);
        console.log('UPLOAD IS ' + percentage + '% DONE!');
    };

    RNFS.uploadFiles({
        toUrl: 'myurl',
        files: [{
            name,
            filename:name,
            filepath: realPath,
        }],
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            Authorization: 'Bearer ' + this.state.token.accessToken,
        },
        body: JSON.stringify({
            name: this.state.nameCan + ' ' + this.state.surename,
            location: this.state.city,
            experience: this.state.experience,
            email: this.state.email,
            phone: this.state.phone,
            file: realPath
            }),
        begin: uploadBegin,
        beginCallback: uploadBegin,
        progressCallback: uploadProgress,
        progress: uploadProgress
    }).then((response) => {
        console.log(response,"<<< Response");
    }).catch((err) => {
        if (err.description) {
            switch (err.description) {
                case "cancelled":
                    console.log("Upload cancelled");
                    break;
                case "empty":
                    console.log("Empty file");
                default:
                    //Unknown
            }
        } else {
            //Weird
        }
        console.log(err);
    });

}

标签: react-nativedocument

解决方案


推荐阅读