Skip to content

Instantly share code, notes, and snippets.

@ChitaGideon
Created October 15, 2015 08:55
Show Gist options
  • Save ChitaGideon/0bc7818a9dcfd4acf50e to your computer and use it in GitHub Desktop.
Save ChitaGideon/0bc7818a9dcfd4acf50e to your computer and use it in GitHub Desktop.
react-native upload file using XMLHttpRequest
_upload() {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://posttestserver.com/post.php');
xhr.onload = () => {
this.setState({isUploading: false});
if (xhr.status !== 200) {
AlertIOS.alert(
'Upload failed',
'Expected HTTP 200 OK response, got ' + xhr.status
);
return;
}
if (!xhr.responseText) {
AlertIOS.alert(
'Upload failed',
'No response payload.'
);
return;
}
var index = xhr.responseText.indexOf('http://www.posttestserver.com/');
if (index === -1) {
AlertIOS.alert(
'Upload failed',
'Invalid response payload.'
);
return;
}
var url = xhr.responseText.slice(index).split('\n')[0];
LinkingIOS.openURL(url);
};
var formdata = new FormData();
if (this.state.randomPhoto) {
formdata.append('image', {...this.state.randomPhoto, name: 'image.jpg'});
}
this.state.textParams.forEach(
(param) => formdata.append(param.name, param.value)
);
xhr.send(formdata);
this.setState({isUploading: true});
}
_fetchRandomPhoto() {
CameraRoll.getPhotos(
{first: PAGE_SIZE},
(data) => {
console.log('isMounted', this._isMounted);
if (!this._isMounted) {
return;
}
var edges = data.edges;
var edge = edges[Math.floor(Math.random() * edges.length)];
var randomPhoto = edge && edge.node && edge.node.image;
if (randomPhoto) {
this.setState({randomPhoto});
}
},
(error) => undefined
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment