Hello Friends 👋,
Welcome To Infinitbility! ❤️
In this article, we create react native application to select and upload videos from the user’s library.
We use react native image picker to select video from user gallery.
Table Of Content
- Create React native application
- Install react native image picker
- implement select video from the user library
- upload a video using fetch
- complete Example to select & upload video in react native
Let’s start with create react native application
Create React native application
- create application
npx react-native init RNVideo
- gradlew clean
cd RNVideo\android && gradlew clean
- launch application
cd .. && npm start
Install react native image picker
For select video from mobile we have to install react native image picker package, follow below steps to install
npm install react-native-image-picker
# RN >= 0.60
cd ios && pod install
# RN < 0.60
react-native link react-native-image-picker
- add permissions to AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
implement select video from user library
Here we are use react native image picker to pic video from user’s gallery
- import image picker
import * as ImagePicker from 'react-native-image-picker';
- select video function to open video library
/**
* Select video & store in state
*/
selectVideo = async () => {
ImagePicker.launchImageLibrary({ mediaType: 'video', includeBase64: true }, (response) => {
console.log(response);
this.setState({ video: response });
})
}
- call selectVideo example
<TouchableOpacity onPress={() => this.selectVideo()} ><Icon name="videocam-outline" size={50} color={this.state.video ? "#fff" : "#6200ee"} /></TouchableOpacity>
upload video using fetch example
For send video file to server we use fetch as 'Content-Type': 'multipart/form-data'
/**
* send feed details to server
*/
uploadVideo = async () => {
this.setState({ loading: true })
const { text, image, video } = this.state;
let errorFlag = false;
if (text) {
errorFlag = true;
this.setState({ textMessage: false });
} else {
errorFlag = false;
this.setState({ textMessage: true })
}
if (errorFlag) {
let formData = new FormData();
if (video) {
formData.append("videoFile", {
name: "name.mp4",
uri: video.uri,
type: 'video/mp4'
});
}
if (image) {
formData.append("image", image.base64);
}
formData.append("text", text);
formData.append("user_id", userDetails.id);
fetch(base_url + 'newFeed.php', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData
})
.then(response => {
return response.json();
})
.then(async (res) => {
this.setState({ loading: false });
console.log(res)
if(res.error == 0){
this.props.navigation.navigate("Feed");
}
})
.catch(error => {
console.log(error);
this.setState({ loading: false });
});
} else {
this.setState({ loading: false });
}
}
complete Example to select & upload video in react native
In complete example, provide example of pic a photo & video from user library and send to the server using fetch.
import React from 'react';
import { StyleSheet, ScrollView, View, Dimensions, TouchableOpacity, Text } from 'react-native';
import { TextInput, Button } from 'react-native-paper';
import Icon from 'react-native-vector-icons/Ionicons';
import * as ImagePicker from 'react-native-image-picker';
const screen = Dimensions.get('window');
export default class NewFeedScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
text: "", // to store text input
textMessage: false, // text input message flag
loading: false, // manage loader
image: "", // store image
video: "", // store video
}
}
/**
* Select image and store in state
*/
selectImage = async () => {
ImagePicker.launchImageLibrary(
{
mediaType: 'photo',
includeBase64: true,
maxHeight: 200,
maxWidth: 200,
},
(response) => {
console.log(response);
this.setState({ image: response });
},
)
}
/**
* Select video & store in state
*/
selectVideo = async () => {
ImagePicker.launchImageLibrary({ mediaType: 'video', includeBase64: true }, (response) => {
console.log(response);
this.setState({ video: response });
})
}
/**
* send feed details to server
*/
createNewFeed = async () => {
this.setState({ loading: true })
const { text, image, video } = this.state;
let errorFlag = false;
if (text) {
errorFlag = true;
this.setState({ textMessage: false });
} else {
errorFlag = false;
this.setState({ textMessage: true })
}
if (errorFlag) {
let formData = new FormData();
if (video) {
formData.append("videoFile", {
name: "name.mp4",
uri: video.uri,
type: 'video/mp4'
});
}
if (image) {
formData.append("image", image.base64);
}
formData.append("text", text);
formData.append("user_id", userDetails.id);
var base_url = "https://yourdomain.com/";
fetch(base_url + 'newFeed.php', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData
})
.then(response => {
return response.json();
})
.then(async (res) => {
this.setState({ loading: false });
console.log(res)
if(res.error == 0){
this.props.navigation.navigate("Feed");
}
})
.catch(error => {
console.log(error);
this.setState({ loading: false });
});
} else {
this.setState({ loading: false });
}
}
render() {
return (
<View style={styles.SplashLayout}>
<ScrollView>
<View style={styles.inputLayout}>
<TextInput
label="Text"
value={this.state.text}
multiline={true}
numberOfLines={5}
onChangeText={(text) => this.setState({ text })}
/>
{
this.state.textMessage && <Text style={styles.textDanger}>{"Text is required"}</Text>
}
</View>
<View style={styles.MediaLayout}>
<View style={[styles.Media, { marginRight: 10, backgroundColor: this.state.image ? "#6200ee" : "#ffffff" }]}>
<TouchableOpacity onPress={() => this.selectImage()} ><Icon name="image-outline" size={50} color={this.state.image ? "#fff" : "#6200ee"} /></TouchableOpacity>
</View>
<View style={[styles.Media, { marginLeft: 10, backgroundColor: this.state.video ? "#6200ee" : "#ffffff" }]}>
<TouchableOpacity onPress={() => this.selectVideo()} ><Icon name="videocam-outline" size={50} color={this.state.video ? "#fff" : "#6200ee"} /></TouchableOpacity>
</View>
</View>
<View style={styles.inputLayout}>
<Button icon="plus" mode="contained" onPress={() => this.createNewFeed()}>
Feed
</Button>
</View>
</ScrollView>
{/* loader */}
{
this.state.loading && <Text>Loading</Text>
}
</View>
)
}
}
const styles = StyleSheet.create({
SplashLayout: {
flex: 1,
},
inputLayout: {
paddingHorizontal: 20,
paddingVertical: 20,
},
textDanger: {
color: "#dc3545"
},
MediaLayout: {
paddingHorizontal: 20,
width: screen.width - 40,
flex: 1,
flexDirection: 'row',
alignItems: "center"
},
Media: {
width: (screen.width - 60) / 2,
height: (screen.width - 60) / 2,
backgroundColor: "#fff",
borderWidth: 1,
borderRadius: 10,
borderColor: "#fff",
justifyContent: "center",
alignItems: "center"
}
});
More From React Native Tutorial
Basics
1. Introduction To React Native
2. React Native Environment Setup using expo
3. React Native Environment Setup for windows
4. React Native Environment setup on Mac OS
5. React Native Environment setup on linux
6. React Native Project Structure
Advances
4. React Native DatepickerAndroid
5. React native ScrollView scroll to position
6. How to align icon with text in react native
8. React Native Firebase Crashlytics
Error & Issue Solution
1. Task :app:transformDexArchiveWithDexMergerForDebug FAILED In React Native
2. Expiring Daemon because JVM heap space is exhausted In React Native
3. Task :app:transformNativeLibsWithMergeJniLibsForDebug FAILED In React Native
5. App crashed immediately after install react native video or track player
6. how to delete SQLite database in android react native
7. React native material dropdown twice click issue
8. How to get the current route in react-navigation?
9. how to disable drawer on the drawer navigation screen?
10. Image not showing in ios 14 react native
11. React Native image picker launchimagelibrary on second time issue
12. how to open any link from react native render Html
13. Network request failed in react native fetch
14. React Native upload video example
Thanks for reading…