React Native Uploaded File Not Available Immediately

Contents

  • i Uploading File in React Native
  • ii Why I use FormData for File Uploading in React Native?
  • 3 How to use FormData for File Uploading in React Native?
  • 4 What Nosotros are Going to Create in Uploading File Example?
  • five To Brand a React Native App
  • 6 Installation of Dependency
  • 7 Linking of Dependency
  • eight CocoaPods Installation
  • nine Code for the File Upload in React Native
    • 9.i App.js
  • 10 Server Side PHP Code
    • 10.1 Core PHP Code (upload.php)
    • 10.two PHP CodeIgniter Lawmaking
  • 11 To Run the React Native App
  • 12 Output Screenshots

Uploading File in React Native

In this postal service, I'll evidence you how to Upload File/Image to Server with Grade Information in React Native. This example will cover how to pick any file from the file system and upload it to the server. I have too shared the server-side PHP lawmaking with the React Native File upload example.

If you noticed the title we are going to use FormData to upload the File on the server because I personally do non like to add third-party dependencies in my projects as long as using those dependencies is the last selection.

Why I utilize FormData for File Uploading in React Native?

If you search for the file uploading examples in React Native over the net you lot volition find many examples and most of them have used external 3rd party dependencies to upload the file on the server, but I personally try to avoid the third-party dependencies and similar to detect the other solution and FormData is one of them. The reason for avoiding 3rd-party dependencies and using FormData is

  1. 3rd-party dependencies can brand your projection bulky
  2. Managing the proper version of dependencies
  3. After the major update of the dependencies, you need to update the project besides
  4. It is very tough to update others lawmaking in case of small update required
  5. The special thing about FormData is that network methods, such as fetch, can accept a FormData object as a body. It is encoded and sent out with Content-Type: multipart/grade-data.

These are the primary reasons for which I use FormData for File Uploading.

How to use FormData for File Uploading in React Native?

Uploading a file using FormDate is very uncomplicated. It is divided into iii steps:

  1. Option a file using any file picker. Here I am using react-native-document-picker for file picking
                  const res = await DocumentPicker.option({     type: [DocumentPicker.types.allFiles], }); this.setState({ singleFile: res });            
  2. Create FormData by creating an object and appending the values you want to send to the server
                  const data = new FormData(); data.append('name', 'Image Upload'); information.append('file_attachment', fileToUpload);            
  3. Using fetch method calling a file upload web service which will send the created FormData as a multipart/form-data to upload the file
                  let uploadImage = async () => {     //Check if any file is selected or not     if (singleFile != goose egg) {       //If file selected then create FormData       const fileToUpload = singleFile;       const data = new FormData();       information.suspend('name', 'Image Upload');       information.suspend('file_attachment', fileToUpload);       let res = await fetch(         'http://localhost//webservice/user/uploadImage',         {           method: 'post',           body: data,           headers: {             'Content-Type': 'multipart/grade-data; ',           },         }       );       permit responseJson = await res.json();       if (responseJson.condition == ane) {         warning('Upload Successful');       }     } else {       //if no file selected the testify alert       alert('Please Select File kickoff');     } };            

What We are Going to Create in Uploading File Example?

In this instance, Nosotros are going to create one Screen with two buttons. One button to pick the file from the file arrangement and another push to upload the file on the server.

If you lot face whatever challenge with the file picker then you tin see Example of File Picker in React Native it volition assist you to solve your issues. At present let's go started with the Instance.

To Make a React Native App

Getting started with React Native will help you to know more than near the way yous tin can make a React Native project. We are going to utilise react-native init to brand our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

          npm install -g react-native-cli        

Run the following commands to create a new React Native project

          react-native init ProjectName        

If you lot want to start a new projection with a specific React Native version, you can use the --version argument:

          react-native init ProjectName --version X.XX.Ten        
          react-native init ProjectName --version react-native@next        

This will brand a project structure with an alphabetize file named App.js in your project directory.

Installation of Dependency

As I mentioned, to pick a file we are going to usereact-native-document-picker which provides DocumentPicker component. To use react-native-certificate-picker we need to install it using the following commands

Open the last and leap into your project

          cd ProjectName        

Run the following control

          npm install react-native-document-picker --save        

Linking of Dependency

Afterwards the updation of React Native 0.lx, they have introduced autolinking feature means nosotros do non crave to link the library but they have also mentioned that some libraries need linking and react-native-document-picker is ane of those cases. So for that, nosotros need to link the library using

          react-native link react-native-document-picker        

CocoaPods Installation

Now nosotros need to install pods

          cd ios && pod install && cd ..        

Code for the File Upload in React Native

Open App.js in whatever code editor and replace the lawmaking with the post-obit code

App.js

          // Case to Pick and Upload files in React Native // https://aboutreact.com/file-uploading-in-react-native/  // Import React import React, { useState } from 'react'; // Import core components import {   StyleSheet,   Text,   View,   TouchableOpacity } from 'react-native';  // Import Certificate Picker import DocumentPicker from 'react-native-certificate-picker';  const App = () => {   const [singleFile, setSingleFile] = useState(zippo);    const uploadImage = async () => {     // Check if whatsoever file is selected or non     if (singleFile != null) {       // If file selected then create FormData       const fileToUpload = singleFile;       const data = new FormData();       data.suspend('proper noun', 'Epitome Upload');       data.append('file_attachment', fileToUpload);       // Please alter file upload URL       let res = expect fetch(         'http://localhost/upload.php',         {           method: 'mail',           body: information,           headers: {             'Content-Type': 'multipart/grade-data; ',           },         }       );       let responseJson = expect res.json();       if (responseJson.status == one) {         alert('Upload Successful');       }     } else {       // If no file selected the show alert       alert('Delight Select File first');     }   };    const selectFile = async () => {     // Opening Document Picker to select one file     try {       const res = wait DocumentPicker.selection({         // Provide which type of file yous want user to selection         type: [DocumentPicker.types.allFiles],         // There can me more options too         // DocumentPicker.types.allFiles         // DocumentPicker.types.images         // DocumentPicker.types.plainText         // DocumentPicker.types.audio         // DocumentPicker.types.pdf       });       // Press the log realted to the file       panel.log('res : ' + JSON.stringify(res));       // Setting the state to show unmarried file attributes       setSingleFile(res);     } grab (err) {       setSingleFile(nix);       // Handling whatever exception (If any)       if (DocumentPicker.isCancel(err)) {         // If user canceled the document choice         alarm('Canceled');       } else {         // For Unknown Fault         alert('Unknown Mistake: ' + JSON.stringify(err));         throw err;       }     }   };   return (     <View style={styles.mainBody}>       <View style={{ alignItems: 'eye' }}>         <Text fashion={{ fontSize: 30, textAlign: 'center' }}>           React Native File Upload Example         </Text>         <Text           mode={{             fontSize: 25,             marginTop: 20,             marginBottom: 30,             textAlign: 'centre',           }}>           www.aboutreact.com         </Text>       </View>       {/*Showing the information of selected Unmarried file*/}       {singleFile != null ? (         <Text way={styles.textStyle}>           File Name: {singleFile.proper name ? singleFile.name : ''}           {'\northward'}           Type: {singleFile.type ? singleFile.type : ''}           {'\n'}           File Size: {singleFile.size ? singleFile.size : ''}           {'\north'}           URI: {singleFile.uri ? singleFile.uri : ''}           {'\n'}         </Text>       ) : zilch}       <TouchableOpacity         style={styles.buttonStyle}         activeOpacity={0.5}         onPress={selectFile}>         <Text style={styles.buttonTextStyle}>Select File</Text>       </TouchableOpacity>       <TouchableOpacity         way={styles.buttonStyle}         activeOpacity={0.5}         onPress={uploadImage}>         <Text style={styles.buttonTextStyle}>Upload File</Text>       </TouchableOpacity>     </View>   ); };  const styles = StyleSheet.create({   mainBody: {     flex: 1,     justifyContent: 'center',     padding: 20,   },   buttonStyle: {     backgroundColor: '#307ecc',     borderWidth: 0,     color: '#FFFFFF',     borderColor: '#307ecc',     acme: 40,     alignItems: 'center',     borderRadius: 30,     marginLeft: 35,     marginRight: 35,     marginTop: xv,   },   buttonTextStyle: {     color: '#FFFFFF',     paddingVertical: ten,     fontSize: 16,   },   textStyle: {     backgroundColor: '#fff',     fontSize: 15,     marginTop: 16,     marginLeft: 35,     marginRight: 35,     textAlign: 'eye',   }, });  export default App;        

Server Side PHP Lawmaking

Please find the server-side PHP code below. Y'all will need to prepare a local server to utilise this Script.

Cadre PHP Code (upload.php)

          <?php   if(!empty($_FILES['file_attachment']['proper name']))   {     $target_dir = "uploads/";     if (!file_exists($target_dir))     {       mkdir($target_dir, 0777);     }     $target_file =       $target_dir . basename($_FILES["file_attachment"]["name"]);     $imageFileType =        strtolower(pathinfo($target_file,PATHINFO_EXTENSION));     // Bank check if file already exists     if (file_exists($target_file)) {       repeat json_encode(          array(            "status" => 0,            "data" => array()            ,"msg" => "Deplorable, file already exists."          )       );       die();     }     // Check file size     if ($_FILES["file_attachment"]["size"] > 50000000) {       echo json_encode(          array(            "status" => 0,            "data" => array(),            "msg" => "Sorry, your file is too big."          )        );       die();     }     if (       move_uploaded_file(         $_FILES["file_attachment"]["tmp_name"], $target_file       )     ) {       repeat json_encode(         array(           "status" => 1,           "data" => array(),           "msg" => "The file " .                     basename( $_FILES["file_attachment"]["proper name"]) .                    " has been uploaded."));     } else {       echo json_encode(         array(           "status" => 0,           "data" => assortment(),           "msg" => "Sad, there was an error uploading your file."         )       );     }   } ?>        

PHP CodeIgniter Code

          /*  Update Images*/ public part uploadImage() {	   if(!empty($_FILES['file_attachment']['name'])) {     $res        = array();     $proper name       = 'file_attachment';     $imagePath 	= 'avails/upload/file_attachment';     $temp       = explode(".",$_FILES['file_attachment']['name']);     $extension 	= stop($temp);     $filenew 	= str_replace(                     $_FILES['file_attachment']['name'],                     $name,                     $_FILES['file_attachment']['proper noun']) .                      '_' . time() . '' . "." . $extension;  		     $config['file_name']   = $filenew;     $config['upload_path'] = $imagePath;     $this->upload->initialize($config);     $this->upload->set_allowed_types('*');     $this->upload->set_filename($config['upload_path'],$filenew);     if(!$this->upload->do_upload('file_attachment')) {       $data = array('msg' => $this->upload->display_errors());     } else {       $data = $this->upload->data();	       if(!empty($data['file_name'])){         $res['image_url'] = 'assets/upload/file_attachment/' .                             $data['file_name'];        }       if (!empty($res)) { 	echo json_encode(           assortment(             "status" => one,             "data" => assortment(),             "msg" => "upload successfully",             "base_url" => base_url(),             "count" => "0"           )         );       }else{ 	repeat json_encode(           assortment(             "status" => 1,             "data" => assortment(),             "msg" => "not establish",             "base_url" => base_url(),             "count" => "0"           )         );       }     }   } }        

To Run the React Native App

Open the terminal again and bound into your project using.

          cd ProjectName        

To run the project on an Android Virtual Device or on real debugging device

          react-native run-android        

or on the iOS Simulator by running (macOS but)

          react-native run-ios        

Download Source Code

Output Screenshots

File Upload 1

This is how you can upload File/Image to Server with Form Data in React Native. If yous take any doubts or you want to share something about the topic you lot can comment below or contact us here. At that place will be more than posts coming soon. Stay tuned!

Hope you liked it. 🙂

jonesexis1991.blogspot.com

Source: https://aboutreact.com/file-uploading-in-react-native/

0 Response to "React Native Uploaded File Not Available Immediately"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel