简体   繁体   中英

React Native fetch API POST file - Network Request Failed

I am trying to do the following:

  1. Select a file on my mobile device in a React Native app using Expo
  2. Send that file to my PHP (Laravel) server using my application API and the fetch API built into React Native

The file is a .config file in XML format. My code is below:

const XHR = new XMLHttpRequest(),
FD  = new FormData();

FD.append('xmldata', this.state.file);
FD.append('meterid', 113);

XHR.addEventListener('load', function(event) {
    console.log('SUCCESS');
});

XHR.addEventListener(' error', function(event) {
    alert('Error');
});

XHR.onreadystatechange = function () {
    console.log(XHR.status);
};

XHR.open('POST', MY_API_URL);

XHR.send(FD);

My code is working on iOS, however I cannot get it working on Android devices. When I run this code on Android it hangs and doesn't give me any response. Does anyone know where I am going wrong here? Thanks in advance.

I have managed to solve this by explicitly setting the file type after I select my file. My code to select the file is now the following:

let result = await DocumentPicker.getDocumentAsync({});
result.type = "application/config";

this.setState({
    file: result
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM