This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Sample React Native App | |
* https://github.com/facebook/react-native | |
* @flow | |
*/ | |
import React, { Component } from 'react'; | |
import { | |
AppRegistry, | |
StyleSheet, | |
Text, | |
View, | |
TextInput, | |
TouchableOpacity | |
} from 'react-native' | |
import RNFetchBlob from 'react-native-fetch-blob' | |
export default class blob extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
url: 'https://images3.alphacoders.com/710/710804.jpg', | |
path: null, | |
received: 0, | |
total: 0, | |
task: null | |
} | |
} | |
download = () => { | |
const url = this.state.url | |
const filename = 'john-snow.jpg' | |
const path = RNFetchBlob.fs.dirs.DownloadDir + '/' + filename | |
const task = new RNFetchBlob | |
.config({ | |
fileCache: true, | |
path | |
}) | |
.fetch('GET', url) | |
// set task | |
this.setState({ task }) | |
task.progress({ interval: 100 }, (received, total) => { | |
this.setState({ | |
received: ~~received, | |
total: ~~total | |
}) | |
}) | |
.then((res) => { | |
console.log(' [ DONWLOAD IS COMPLETED ] ') | |
this.setState({ path: res.path() }) | |
}, e => { | |
console.log(' [ DONWLOAD IS CANCELLED ] ') | |
console.log(e) | |
}) | |
} | |
cancel = () => { | |
this.state.task.cancel() | |
} | |
openfile = () => { | |
RNFetchBlob.ios.openDocument(this.state.path).then(r => r, e => e) | |
} | |
render() { | |
return ( | |
<View style={styles.container}> | |
<TextInput | |
value={this.state.url} | |
onChangeText={(url) => this.setState({url})} | |
placeholder='enter url' | |
/> | |
{ | |
this.state.total > 0 && | |
<Text>{this.state.received} / {this.state.total}</Text> | |
} | |
<TouchableOpacity onPress={this.download}> | |
<Text>Download</Text> | |
</TouchableOpacity> | |
<TouchableOpacity onPress={this.cancel}> | |
<Text>Cancel</Text> | |
</TouchableOpacity> | |
{ | |
this.state.path != null && | |
<View style={{ marginTop: 40 }}> | |
<TouchableOpacity onPress={this.openfile}> | |
<Text>Open { this.state.path }</Text> | |
</TouchableOpacity> | |
</View> | |
} | |
</View> | |
); | |
} | |
} | |
const styles = StyleSheet.create({ | |
container: { | |
flex: 1, | |
marginTop: 100 | |
} | |
}); | |
AppRegistry.registerComponent('blob', () => blob); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment