Skip to content

Instantly share code, notes, and snippets.

@raminious
Created November 16, 2016 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raminious/17d3d3043a25e7acc57d0b82a969ba1e to your computer and use it in GitHub Desktop.
Save raminious/17d3d3043a25e7acc57d0b82a969ba1e to your computer and use it in GitHub Desktop.
/**
* 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