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
1npx react-native init RNVideo
- gradlew clean
1cd RNVideo\android && gradlew clean
- launch application
1cd .. && 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
1npm install react-native-image-picker23# RN >= 0.604cd ios && pod install56# RN < 0.607react-native link react-native-image-picker
- add permissions to AndroidManifest.xml
1<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>2<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
1import * as ImagePicker from 'react-native-image-picker';
- select video function to open video library
1/**2* Select video & store in state3*/4selectVideo = async () => {5 ImagePicker.launchImageLibrary({ mediaType: 'video', includeBase64: true }, (response) => {6 console.log(response);7 this.setState({ video: response });8 })9}
- call selectVideo example
1<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'
1/**2* send feed details to server3*/4uploadVideo = async () => {5 this.setState({ loading: true })6 const { text, image, video } = this.state;7 let errorFlag = false;89 if (text) {10 errorFlag = true;11 this.setState({ textMessage: false });12 } else {13 errorFlag = false;14 this.setState({ textMessage: true })15 }1617 if (errorFlag) {18 let formData = new FormData();1920 if (video) {2122 formData.append("videoFile", {23 name: "name.mp4",24 uri: video.uri,25 type: 'video/mp4'26 });27 }2829 if (image) {30 formData.append("image", image.base64);31 }3233 formData.append("text", text);34 formData.append("user_id", userDetails.id);3536 fetch(base_url + 'newFeed.php', {37 method: 'POST',38 headers: {39 'Content-Type': 'multipart/form-data',40 },41 body: formData42 })43 .then(response => {44 return response.json();45 })46 .then(async (res) => {47 this.setState({ loading: false });48 console.log(res)4950 if(res.error == 0){51 this.props.navigation.navigate("Feed");52 }5354 })55 .catch(error => {56 console.log(error);57 this.setState({ loading: false });58 });59 } else {60 this.setState({ loading: false });61 }62}
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.
1import React from 'react';2import { StyleSheet, ScrollView, View, Dimensions, TouchableOpacity, Text } from 'react-native';3import { TextInput, Button } from 'react-native-paper';4import Icon from 'react-native-vector-icons/Ionicons';5import * as ImagePicker from 'react-native-image-picker';67const screen = Dimensions.get('window');8export default class NewFeedScreen extends React.Component {91011 constructor(props) {12 super(props);1314 this.state = {15 text: "", // to store text input16 textMessage: false, // text input message flag17 loading: false, // manage loader18 image: "", // store image19 video: "", // store video20 }21 }2223 /**24 * Select image and store in state25 */26 selectImage = async () => {2728 ImagePicker.launchImageLibrary(29 {30 mediaType: 'photo',31 includeBase64: true,32 maxHeight: 200,33 maxWidth: 200,34 },35 (response) => {36 console.log(response);37 this.setState({ image: response });38 },39 )40 }4142 /**43 * Select video & store in state44 */45 selectVideo = async () => {46 ImagePicker.launchImageLibrary({ mediaType: 'video', includeBase64: true }, (response) => {47 console.log(response);48 this.setState({ video: response });49 })50 }5152 /**53 * send feed details to server54 */55 createNewFeed = async () => {56 this.setState({ loading: true })57 const { text, image, video } = this.state;58 let errorFlag = false;5960 if (text) {61 errorFlag = true;62 this.setState({ textMessage: false });63 } else {64 errorFlag = false;65 this.setState({ textMessage: true })66 }6768 if (errorFlag) {69 let formData = new FormData();7071 if (video) {7273 formData.append("videoFile", {74 name: "name.mp4",75 uri: video.uri,76 type: 'video/mp4'77 });78 }7980 if (image) {81 formData.append("image", image.base64);82 }8384 formData.append("text", text);85 formData.append("user_id", userDetails.id);86 var base_url = "https://yourdomain.com/";87 fetch(base_url + 'newFeed.php', {88 method: 'POST',89 headers: {90 'Content-Type': 'multipart/form-data',91 },92 body: formData93 })94 .then(response => {95 return response.json();96 })97 .then(async (res) => {98 this.setState({ loading: false });99 console.log(res)100101 if(res.error == 0){102 this.props.navigation.navigate("Feed");103 }104105 })106 .catch(error => {107 console.log(error);108 this.setState({ loading: false });109 });110 } else {111 this.setState({ loading: false });112 }113 }114115116 render() {117 return (118 <View style={styles.SplashLayout}>119 <ScrollView>120 <View style={styles.inputLayout}>121 <TextInput122 label="Text"123 value={this.state.text}124 multiline={true}125 numberOfLines={5}126 onChangeText={(text) => this.setState({ text })}127 />128 {129 this.state.textMessage && <Text style={styles.textDanger}>{"Text is required"}</Text>130 }131 </View>132 <View style={styles.MediaLayout}>133 <View style={[styles.Media, { marginRight: 10, backgroundColor: this.state.image ? "#6200ee" : "#ffffff" }]}>134 <TouchableOpacity onPress={() => this.selectImage()} ><Icon name="image-outline" size={50} color={this.state.image ? "#fff" : "#6200ee"} /></TouchableOpacity>135 </View>136 <View style={[styles.Media, { marginLeft: 10, backgroundColor: this.state.video ? "#6200ee" : "#ffffff" }]}>137 <TouchableOpacity onPress={() => this.selectVideo()} ><Icon name="videocam-outline" size={50} color={this.state.video ? "#fff" : "#6200ee"} /></TouchableOpacity>138 </View>139 </View>140 <View style={styles.inputLayout}>141 <Button icon="plus" mode="contained" onPress={() => this.createNewFeed()}>142 Feed143 </Button>144 </View>145 </ScrollView>146 {/* loader */}147 {148 this.state.loading && <Text>Loading</Text>149 }150 </View>151 )152 }153154}155156const styles = StyleSheet.create({157 SplashLayout: {158 flex: 1,159 },160 inputLayout: {161 paddingHorizontal: 20,162 paddingVertical: 20,163 },164 textDanger: {165 color: "#dc3545"166 },167 MediaLayout: {168 paddingHorizontal: 20,169 width: screen.width - 40,170 flex: 1,171 flexDirection: 'row',172 alignItems: "center"173 },174 Media: {175 width: (screen.width - 60) / 2,176 height: (screen.width - 60) / 2,177 backgroundColor: "#fff",178 borderWidth: 1,179 borderRadius: 10,180 borderColor: "#fff",181 justifyContent: "center",182 alignItems: "center"183 }184});
More From React Native Tutorial
Basics
- Introduction To React Native
- React Native Environment Setup using expo
- React Native Environment Setup for windows
- React Native Environment setup on Mac OS
- React Native Environment setup on linux
- React Native Project Structure
- React Native State
- React Native Props
- React Native Styling
- React Native Flexbox
- React Native Text
- React Native Textinput
- React Native Commands
- React Native ScrollView
Advances
- React Native Dark Mode
- React Native Fonts
- React Native SQLite
- React Native DatepickerAndroid
- React native ScrollView scroll to position
- How to align icon with text in react native
- React Native Image
- React Native Firebase Crashlytics
- React Native Async Storage
- React Native Share
Error & Issue Solution
- Task :app:transformDexArchiveWithDexMergerForDebug FAILED In React Native
- Expiring Daemon because JVM heap space is exhausted In React Native
- Task :app:transformNativeLibsWithMergeJniLibsForDebug FAILED In React Native
- Unable to determine the current character, it is not a string, number, array, or object in react native
- App crashed immediately after install react native video or track player
- how to delete SQLite database in android react native
- React native material dropdown twice click issue
- How to get the current route in react-navigation?
- how to disable drawer on the drawer navigation screen?
- Image not showing in ios 14 react native
- React Native image picker launchimagelibrary on second time issue
- how to open any link from react native render Html
- Network request failed in react native fetch
- React Native upload video example