Navigate back to the homepage

How to select and upload video in react native

Infinitbility
React Native
March 27th, 2021 · 1 min read
How to select and upload video in react native

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

  1. Create React native application
  2. Install react native image picker
  3. implement select video from the user library
  4. upload a video using fetch
  5. 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-picker
2
3# RN >= 0.60
4cd ios && pod install
5
6# RN < 0.60
7react-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 state
3*/
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 server
3*/
4uploadVideo = async () => {
5 this.setState({ loading: true })
6 const { text, image, video } = this.state;
7 let errorFlag = false;
8
9 if (text) {
10 errorFlag = true;
11 this.setState({ textMessage: false });
12 } else {
13 errorFlag = false;
14 this.setState({ textMessage: true })
15 }
16
17 if (errorFlag) {
18 let formData = new FormData();
19
20 if (video) {
21
22 formData.append("videoFile", {
23 name: "name.mp4",
24 uri: video.uri,
25 type: 'video/mp4'
26 });
27 }
28
29 if (image) {
30 formData.append("image", image.base64);
31 }
32
33 formData.append("text", text);
34 formData.append("user_id", userDetails.id);
35
36 fetch(base_url + 'newFeed.php', {
37 method: 'POST',
38 headers: {
39 'Content-Type': 'multipart/form-data',
40 },
41 body: formData
42 })
43 .then(response => {
44 return response.json();
45 })
46 .then(async (res) => {
47 this.setState({ loading: false });
48 console.log(res)
49
50 if(res.error == 0){
51 this.props.navigation.navigate("Feed");
52 }
53
54 })
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';
6
7const screen = Dimensions.get('window');
8export default class NewFeedScreen extends React.Component {
9
10
11 constructor(props) {
12 super(props);
13
14 this.state = {
15 text: "", // to store text input
16 textMessage: false, // text input message flag
17 loading: false, // manage loader
18 image: "", // store image
19 video: "", // store video
20 }
21 }
22
23 /**
24 * Select image and store in state
25 */
26 selectImage = async () => {
27
28 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 }
41
42 /**
43 * Select video & store in state
44 */
45 selectVideo = async () => {
46 ImagePicker.launchImageLibrary({ mediaType: 'video', includeBase64: true }, (response) => {
47 console.log(response);
48 this.setState({ video: response });
49 })
50 }
51
52 /**
53 * send feed details to server
54 */
55 createNewFeed = async () => {
56 this.setState({ loading: true })
57 const { text, image, video } = this.state;
58 let errorFlag = false;
59
60 if (text) {
61 errorFlag = true;
62 this.setState({ textMessage: false });
63 } else {
64 errorFlag = false;
65 this.setState({ textMessage: true })
66 }
67
68 if (errorFlag) {
69 let formData = new FormData();
70
71 if (video) {
72
73 formData.append("videoFile", {
74 name: "name.mp4",
75 uri: video.uri,
76 type: 'video/mp4'
77 });
78 }
79
80 if (image) {
81 formData.append("image", image.base64);
82 }
83
84 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: formData
93 })
94 .then(response => {
95 return response.json();
96 })
97 .then(async (res) => {
98 this.setState({ loading: false });
99 console.log(res)
100
101 if(res.error == 0){
102 this.props.navigation.navigate("Feed");
103 }
104
105 })
106 .catch(error => {
107 console.log(error);
108 this.setState({ loading: false });
109 });
110 } else {
111 this.setState({ loading: false });
112 }
113 }
114
115
116 render() {
117 return (
118 <View style={styles.SplashLayout}>
119 <ScrollView>
120 <View style={styles.inputLayout}>
121 <TextInput
122 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 Feed
143 </Button>
144 </View>
145 </ScrollView>
146 {/* loader */}
147 {
148 this.state.loading && <Text>Loading</Text>
149 }
150 </View>
151 )
152 }
153
154}
155
156const 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

  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
  7. React Native State
  8. React Native Props
  9. React Native Styling
  10. React Native Flexbox
  11. React Native Text
  12. React Native Textinput
  13. React Native Commands
  14. React Native ScrollView

Advances

  1. React Native Dark Mode
  2. React Native Fonts
  3. React Native SQLite
  4. React Native DatepickerAndroid
  5. React native ScrollView scroll to position
  6. How to align icon with text in react native
  7. React Native Image
  8. React Native Firebase Crashlytics
  9. React Native Async Storage
  10. React Native Share

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
  4. Unable to determine the current character, it is not a string, number, array, or object 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

Looking For React Native Tutorial?

we are trying to create the best Tutorial for react native developers.

When you want a daily updates about React Native Tutorial or infinitbility update subscribe to our newsletter.

Read React Native Tutorial

Request New Tutorial or Article on mail [email protected]

Join our email list and get notified about new content

No worries, I respect your privacy and I will never abuse your email.

Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.

More articles from Infinitbility

Network request failed in react native fetch

Network request failed in react native fetch

Solve HTTP and HTTPS Network request failed issue in react native fetch

March 15th, 2021 · 1 min read
how to open any link from react native render Html

how to open any link from react native render Html

react native render html link click issue

February 26th, 2021 · 1 min read
© 2020–2021 Infinitbility
Disclaimer
Link to $https://medium.com/infinitbilityLink to $https://www.facebook.com/InfinitbilityLink to $https://github.com/infinitbilityLink to $https://twitter.com/infinitbilityLink to $https://www.buymeacoffee.com/infinitbilityLink to $mailto:[email protected]