create an img from an uploaded file react
Contents
- 1 Uploading File in React Native
- 2 Why I use FormData for File Uploading in React Native?
- 3 How to apply FormData for File Uploading in React Native?
- four What Nosotros are Going to Create in Uploading File Example?
- v To Brand a React Native App
- half dozen Installation of Dependency
- 7 Linking of Dependency
- 8 CocoaPods Installation
- 9 Code for the File Upload in React Native
- ix.1 App.js
- 10 Server Side PHP Lawmaking
- 10.1 Cadre PHP Code (upload.php)
- x.ii PHP CodeIgniter Code
- eleven To Run the React Native App
- 12 Output Screenshots
Uploading File in React Native
In this post, I'll show y'all how to Upload File/Image to Server with Form Data in React Native. This case will cover how to pick any file from the file system and upload it to the server. I have also shared the server-side PHP code with the React Native File upload case.
If you noticed the title we are going to use FormData to upload the File on the server considering I personally practise not like to add together third-political party dependencies in my projects every bit long as using those dependencies is the final option.
Why I use FormData for File Uploading in React Native?
If you lot search for the file uploading examples in React Native over the net you will discover many examples and nearly of them have used external third party dependencies to upload the file on the server, but I personally endeavor to avoid the tertiary-political party dependencies and similar to discover the other solution and FormData is i of them. The reason for avoiding third-political party dependencies and using FormData is
- Tertiary-party dependencies tin brand your project bulky
- Managing the proper version of dependencies
- Afterwards the major update of the dependencies, you need to update the projection every bit well
- It is very tough to update others code in example of small update required
- The special thing near FormData is that network methods, such as fetch, can accept a FormData object as a torso. It is encoded and sent out with Content-Type: multipart/form-data.
These are the master 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 simple. It is divided into three steps:
- Pick a file using whatsoever 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 });
- 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);
- Using fetch method calling a file upload spider web service which volition transport the created FormData as a multipart/form-information to upload the file
let uploadImage = async () => { //Bank check if whatever file is selected or not if (singleFile != goose egg) { //If file selected then create FormData const fileToUpload = singleFile; const information = new FormData(); data.suspend('name', 'Image Upload'); data.suspend('file_attachment', fileToUpload); permit res = await fetch( 'http://localhost//webservice/user/uploadImage', { method: 'post', body: data, headers: { 'Content-Type': 'multipart/form-information; ', }, } ); let responseJson = expect res.json(); if (responseJson.condition == 1) { alert('Upload Successful'); } } else { //if no file selected the bear witness alarm warning('Delight Select File first'); } };
What We are Going to Create in Uploading File Example?
In this instance, We are going to create one Screen with 2 buttons. One button to pick the file from the file system and another push to upload the file on the server.
If you face whatsoever claiming with the file picker then yous can see Example of File Picker in React Native it will help y'all to solve your problems. Now allow'due south get started with the Example.
To Make a React Native App
Getting started with React Native will help y'all to know more virtually the mode y'all can brand a React Native project. We are going to use react-native init to make our React Native App. Assuming that y'all have node installed, y'all can use npm to install the react-native-cli
command line utility. Open up the terminal and become 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 beginning a new projection with a specific React Native version, yous can use the --version argument:
react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next
This will make a project structure with an index file named App.js in your project directory.
Installation of Dependency
Equally I mentioned, to pick a file we are going to applyreact-native-document-picker
which provides DocumentPicker
component. To utilise react-native-document-picker
we need to install it using the following commands
Open the terminal and jump into your projection
cd ProjectName
Run the following command
npm install react-native-certificate-picker --save
Linking of Dependency
After the updation of React Native 0.lx, they have introduced autolinking feature ways we practice not require to link the library but they accept also mentioned that some libraries need linking and react-native-document-picker is one of those cases. So for that, we need to link the library using
react-native link react-native-document-picker
CocoaPods Installation
Now we need to install pods
cd ios && pod install && cd ..
Code for the File Upload in React Native
Open App.js in any code editor and supplant the code with the post-obit code
App.js
// Instance to Selection 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 Document Picker import DocumentPicker from 'react-native-certificate-picker'; const App = () => { const [singleFile, setSingleFile] = useState(null); const uploadImage = async () => { // Check if whatever file is selected or not if (singleFile != null) { // If file selected then create FormData const fileToUpload = singleFile; const data = new FormData(); data.suspend('name', 'Prototype Upload'); data.suspend('file_attachment', fileToUpload); // Delight alter file upload URL allow res = await fetch( 'http://localhost/upload.php', { method: 'mail service', body: data, headers: { 'Content-Type': 'multipart/form-data; ', }, } ); permit responseJson = await res.json(); if (responseJson.status == one) { alert('Upload Successful'); } } else { // If no file selected the show alert warning('Delight Select File outset'); } }; const selectFile = async () => { // Opening Certificate Picker to select i file endeavour { const res = await DocumentPicker.pick({ // Provide which type of file you want user to selection blazon: [DocumentPicker.types.allFiles], // There can me more options as well // DocumentPicker.types.allFiles // DocumentPicker.types.images // DocumentPicker.types.plainText // DocumentPicker.types.sound // DocumentPicker.types.pdf }); // Printing 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(nada); // Handling any exception (If any) if (DocumentPicker.isCancel(err)) { // If user canceled the certificate selection warning('Canceled'); } else { // For Unknown Error alert('Unknown Mistake: ' + JSON.stringify(err)); throw err; } } }; return ( <View style={styles.mainBody}> <View style={{ alignItems: 'center' }}> <Text style={{ fontSize: 30, textAlign: 'center' }}> React Native File Upload Example </Text> <Text style={{ fontSize: 25, marginTop: 20, marginBottom: 30, textAlign: 'center', }}> www.aboutreact.com </Text> </View> {/*Showing the data of selected Single file*/} {singleFile != nada ? ( <Text style={styles.textStyle}> File Proper noun: {singleFile.name ? singleFile.name : ''} {'\north'} Type: {singleFile.type ? singleFile.type : ''} {'\northward'} File Size: {singleFile.size ? singleFile.size : ''} {'\due north'} URI: {singleFile.uri ? singleFile.uri : ''} {'\n'} </Text> ) : null} <TouchableOpacity style={styles.buttonStyle} activeOpacity={0.5} onPress={selectFile}> <Text way={styles.buttonTextStyle}>Select File</Text> </TouchableOpacity> <TouchableOpacity style={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: xx, }, buttonStyle: { backgroundColor: '#307ecc', borderWidth: 0, colour: '#FFFFFF', borderColor: '#307ecc', height: forty, alignItems: 'eye', borderRadius: xxx, marginLeft: 35, marginRight: 35, marginTop: 15, }, buttonTextStyle: { color: '#FFFFFF', paddingVertical: 10, fontSize: 16, }, textStyle: { backgroundColor: '#fff', fontSize: 15, marginTop: 16, marginLeft: 35, marginRight: 35, textAlign: 'center', }, }); export default App;
Server Side PHP Code
Please discover the server-side PHP lawmaking beneath. You volition demand to prepare a local server to use this Script.
Core PHP Lawmaking (upload.php)
<?php if(!empty($_FILES['file_attachment']['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)); // Check if file already exists if (file_exists($target_file)) { echo json_encode( array( "condition" => 0, "data" => array() ,"msg" => "Sorry, file already exists." ) ); dice(); } // Check file size if ($_FILES["file_attachment"]["size"] > 50000000) { repeat json_encode( array( "status" => 0, "data" => array(), "msg" => "Sorry, your file is too large." ) ); die(); } if ( move_uploaded_file( $_FILES["file_attachment"]["tmp_name"], $target_file ) ) { echo json_encode( array( "status" => ane, "data" => assortment(), "msg" => "The file " . basename( $_FILES["file_attachment"]["proper name"]) . " has been uploaded.")); } else { repeat json_encode( array( "status" => 0, "data" => array(), "msg" => "Sorry, there was an error uploading your file." ) ); } } ?>
PHP CodeIgniter Code
/* Update Images*/ public part uploadImage() { if(!empty($_FILES['file_attachment']['name'])) { $res = array(); $name = 'file_attachment'; $imagePath = 'assets/upload/file_attachment'; $temp = explode(".",$_FILES['file_attachment']['name']); $extension = end($temp); $filenew = str_replace( $_FILES['file_attachment']['proper noun'], $name, $_FILES['file_attachment']['name']) . '_' . fourth dimension() . '' . "." . $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')) { $information = array('msg' => $this->upload->display_errors()); } else { $data = $this->upload->information(); if(!empty($data['file_name'])){ $res['image_url'] = 'assets/upload/file_attachment/' . $data['file_name']; } if (!empty($res)) { repeat json_encode( array( "status" => 1, "information" => array(), "msg" => "upload successfully", "base_url" => base_url(), "count" => "0" ) ); }else{ echo json_encode( array( "status" => 1, "data" => array(), "msg" => "not establish", "base_url" => base_url(), "count" => "0" ) ); } } } }
To Run the React Native App
Open the last 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 past running (macOS only)
react-native run-ios
Download Source Code
Output Screenshots
This is how y'all tin upload File/Image to Server with Form Data in React Native. If you have any doubts or you want to share something about the topic y'all tin comment below or contact united states here. In that location volition be more posts coming soon. Stay tuned!
Hope yous liked it. 🙂
Source: https://aboutreact.com/file-uploading-in-react-native/
Post a Comment for "create an img from an uploaded file react"