{"id":2374,"date":"2022-12-01T01:45:45","date_gmt":"2022-11-30T18:45:45","guid":{"rendered":"https:\/\/www.bagi2info.com\/?p=2374"},"modified":"2023-01-04T11:53:51","modified_gmt":"2023-01-04T04:53:51","slug":"cara-upload-file-image-menggunakan-form-data-react-native-expo","status":"publish","type":"post","link":"https:\/\/www.bagi2info.com\/en\/how-to-upload-files-images-using-the-react-native-expo-data-form\/","title":{"rendered":"How to Upload Files\/Images Using the React Native Expo Data Form"},"content":{"rendered":"\r\n<figure class=\"wp-block-image size-full is-style-default\"><a href=\"https:\/\/www.bagi2info.com\/wp-content\/uploads\/2022\/12\/upload.jpg\"><img loading=\"lazy\" decoding=\"async\" width=\"618\" height=\"273\" src=\"https:\/\/www.bagi2info.com\/wp-content\/uploads\/2022\/12\/upload.jpg\" alt=\"upload file \/ gambar\" class=\"wp-image-3273\" srcset=\"https:\/\/www.bagi2info.com\/wp-content\/uploads\/2022\/12\/upload.jpg 618w, https:\/\/www.bagi2info.com\/wp-content\/uploads\/2022\/12\/upload-300x133.jpg 300w\" sizes=\"auto, (max-width: 618px) 100vw, 618px\" \/><\/a><\/figure>\r\n\r\n\r\n<p>Hello friends, back to the react native tutorial, sometimes we want to add a file or image upload function to our application, here is the source code for uploading files\/images using form data in react native Expo. <\/p>\r\n\r\n\r\n\r\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.bagi2info.com\/en\/how-to-upload-files-images-using-the-react-native-expo-data-form\/#Appjs\" >App.js<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.bagi2info.com\/en\/how-to-upload-files-images-using-the-react-native-expo-data-form\/#Uploadphp\" >Upload.php<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Appjs\"><\/span>App.js<span class=\"ez-toc-section-end\"><\/span><\/h2>\r\n\r\n\r\n\r\n<pre title=\"App.js\" class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx line-numbers\">import React, { useState } from 'react';\r\nimport {\r\n  View,\r\n  StyleSheet,\r\n  Alert,\r\n  PermissionsAndroid,\r\n  Text,\r\n  TouchableOpacity,\r\n} from 'react-native';\r\n\r\nimport * as DocumentPicker from 'expo-document-picker';\r\n\r\nexport default function App() {\r\n  const [singleFile, setSingleFile] = useState(null);\r\n\r\n  const checkPermissions = async () => {\r\n    try {\r\n      const result = await PermissionsAndroid.check(\r\n        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE\r\n      );\r\n\r\n      if (!result) {\r\n        const granted = await PermissionsAndroid.request(\r\n          PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,\r\n          {\r\n            title:\r\n              'You need to give storage permission to download and save the file',\r\n            message: 'App needs access to your camera ',\r\n            buttonNeutral: 'Ask Me Later',\r\n            buttonNegative: 'Cancel',\r\n            buttonPositive: 'OK',\r\n          }\r\n        );\r\n        if (granted === PermissionsAndroid.RESULTS.GRANTED) {\r\n          console.log('You can use the camera');\r\n          return true;\r\n        } else {\r\n          Alert.alert('Error', I18n.t('PERMISSION_ACCESS_FILE'));\r\n\r\n          console.log('Camera permission denied');\r\n          return false;\r\n        }\r\n      } else {\r\n        return true;\r\n      }\r\n    } catch (err) {\r\n      console.warn(err);\r\n      return false;\r\n    }\r\n  };\r\n\r\n  const uploadImage = async () => {\r\n    const BASE_URL = 'xxxx';\r\n\r\n    \/\/ Check if any file is selected or not\r\n    if (singleFile != null) {\r\n      \/\/ If file selected then create FormData\r\n      const data = new FormData();\r\n\r\n      data.append('file_attachment', {\r\n        uri: singleFile.uri,\r\n        name: singleFile.name,\r\n        type: singleFile.mimeType,\r\n      });\r\n\r\n      \/\/ return\r\n      try {\r\n        let res = await fetch(BASE_URL + 'tutorial\/upload.php', {\r\n          method: 'post',\r\n          body: data,\r\n          headers: {\r\n            Accept: 'application\/json',\r\n            'Content-Type': 'multipart\/form-data',\r\n          },\r\n          timeout: 5000,\r\n        });\r\n\r\n        let result = await res.json();\r\n        console.log('result', result);\r\n        if (result.status == 1) {\r\n          Alert.alert('Info', result.msg);\r\n        }\r\n      } catch (error) {\r\n        \/\/ Error retrieving data\r\n        \/\/ Alert.alert('Error', error.message);\r\n        console.log('error upload', error);\r\n      }\r\n    } else {\r\n      \/\/ If no file selected the show alert\r\n      Alert.alert('Please Select File first');\r\n    }\r\n  };\r\n\r\n  async function selectFile() {\r\n    try {\r\n      const result = await checkPermissions();\r\n\r\n      if (result) {\r\n        const result = await DocumentPicker.getDocumentAsync({\r\n          copyToCacheDirectory: false,\r\n          type: 'image\/*',\r\n        });\r\n\r\n        if (result.type === 'success') {\r\n          \/\/ Printing the log realted to the file\r\n          console.log('res : ' + JSON.stringify(result));\r\n          \/\/ Setting the state to show single file attributes\r\n          setSingleFile(result);\r\n        }\r\n      }\r\n    } catch (err) {\r\n      setSingleFile(null);\r\n      console.warn(err);\r\n      return false;\r\n    }\r\n  }\r\n\r\n  return (\r\n    &lt;View style={styles.mainBody}>\r\n      &lt;View style={{ alignItems: 'center' }}>\r\n        &lt;Text\r\n          style={{\r\n            fontSize: 30,\r\n            textAlign: 'center',\r\n            marginTop: 20,\r\n            marginBottom: 30,\r\n          }}>\r\n          React Native File Upload Example\r\n        &lt;\/Text>\r\n      &lt;\/View>\r\n      {\/*Showing the data of selected Single file*\/}\r\n      {singleFile != null ? (\r\n        &lt;Text style={styles.textStyle}>\r\n          File Name: {singleFile.name ? singleFile.name : ''}\r\n          {'\\n'}\r\n          Type: {singleFile.type ? singleFile.type : ''}\r\n          {'\\n'}\r\n          File Size: {singleFile.size ? singleFile.size : ''}\r\n          {'\\n'}\r\n          URI: {singleFile.uri ? singleFile.uri : ''}\r\n          {'\\n'}\r\n        &lt;\/Text>\r\n      ) : null}\r\n\r\n      &lt;TouchableOpacity\r\n        style={styles.buttonStyle}\r\n        activeOpacity={0.5}\r\n        onPress={selectFile}>\r\n        &lt;Text style={styles.buttonTextStyle}>Select File&lt;\/Text>\r\n      &lt;\/TouchableOpacity>\r\n\r\n      &lt;TouchableOpacity\r\n        style={styles.buttonStyle}\r\n        activeOpacity={0.5}\r\n        onPress={uploadImage}>\r\n        &lt;Text style={styles.buttonTextStyle}>Upload File&lt;\/Text>\r\n      &lt;\/TouchableOpacity>\r\n    &lt;\/View>\r\n  );\r\n}\r\n\r\nconst styles = StyleSheet.create({\r\n  mainBody: {\r\n    flex: 1,\r\n    justifyContent: 'center',\r\n    padding: 20,\r\n  },\r\n  buttonStyle: {\r\n    backgroundColor: '#307ecc',\r\n    borderWidth: 0,\r\n    color: '#FFFFFF',\r\n    borderColor: '#307ecc',\r\n    height: 40,\r\n    alignItems: 'center',\r\n    borderRadius: 30,\r\n    marginLeft: 35,\r\n    marginRight: 35,\r\n    marginTop: 15,\r\n  },\r\n  buttonTextStyle: {\r\n    color: '#FFFFFF',\r\n    paddingVertical: 10,\r\n    fontSize: 16,\r\n  },\r\n  textStyle: {\r\n    backgroundColor: '#fff',\r\n    fontSize: 15,\r\n    marginTop: 16,\r\n    marginLeft: 35,\r\n    marginRight: 35,\r\n    textAlign: 'center',\r\n  },\r\n});\r\n<\/code><\/pre>\r\n\r\n\r\n\r\n<p><\/p>\r\n\r\n\r\n\r\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Uploadphp\"><\/span>Upload.php<span class=\"ez-toc-section-end\"><\/span><\/h2>\r\n\r\n\r\n\r\n<p>The following API backend files use PHP to copy files from React Native form submissions<\/p>\r\n\r\n\r\n\r\n<pre title=\"tutorial\/upload.php\" class=\"wp-block-code\"><code lang=\"php\" class=\"language-php line-numbers\">&lt;?php\r\nif (!empty($_FILES['file_attachment']['name'])) {\r\n\r\n    $target_dir = \"photos\/\";\r\n\r\n    if (!file_exists($target_dir)) {\r\n        mkdir($target_dir, 0755);\r\n    }\r\n\r\n    $target_file =\r\n        $target_dir . basename($_FILES[\"file_attachment\"][\"name\"]);\r\n    $imageFileType =\r\n        strtolower(pathinfo($target_file, PATHINFO_EXTENSION));\r\n\r\n    \/\/ Check if file already exists\r\n    if (file_exists($target_file)) {\r\n        echo json_encode(\r\n            array(\r\n                \"status\" => 0,\r\n                \"data\" => array(), \"msg\" => \"Sorry, file already exists.\"\r\n            )\r\n        );\r\n        die();\r\n    }\r\n\r\n    \/\/ Check file size\r\n    if ($_FILES[\"file_attachment\"][\"size\"] > 5000000) {\r\n        echo json_encode(\r\n            array(\r\n                \"status\" => 0,\r\n                \"data\" => array(),\r\n                \"msg\" => \"Sorry, your file is too large.\"\r\n            )\r\n        );\r\n        die();\r\n    }\r\n\r\n    if (\r\n        move_uploaded_file(\r\n            $_FILES[\"file_attachment\"][\"tmp_name\"],\r\n            $target_file\r\n        )\r\n    ) {\r\n\r\n        echo json_encode(\r\n            array(\r\n                \"status\" => 1,\r\n                \"data\" => array(),\r\n                \"msg\" => \"The file \" .\r\n                    basename($_FILES[\"file_attachment\"][\"name\"]) .\r\n                    \" has been uploaded.\",\r\n                \"filename\" => $filename\r\n            )\r\n        );\r\n    } else {\r\n        echo json_encode(\r\n            array(\r\n                \"status\" => 0,\r\n                \"data\" => array(),\r\n                \"msg\" => \"Sorry, there was an error uploading your file.\"\r\n            )\r\n        );\r\n    }\r\n}\r\n<\/code><\/pre>\r\n\r\n\r\n\r\n<p>Snack: <\/p>\r\n\r\n\r\n\r\n<p><a href=\"https:\/\/ckk.ai\/upload-file\">https:\/\/ckk.ai\/upload-file<\/a><\/p>\r\n\r\n\r\n\r\n<p>Referensi: <\/p>\r\n\r\n\r\n\r\n<p><a href=\"https:\/\/aboutreact.com\/file-uploading-in-react-native\/\">https:\/\/aboutreact.com\/file-uploading-in-react-native\/<\/a><\/p>\r\n\r\n\r\n<p>Changes: Modified coding using <strong>Expo<\/strong>, added check permissions for android, and replaced the image capture library using <strong>expo-document-picker<\/strong><\/p>\r\n\r\n\r\n\r\n<p><\/p>\r\n","protected":false},"excerpt":{"rendered":"<p>Hello friends, back to the react native tutorial, sometimes we want to add a file or image upload function to our application, here is the source code for uploading files\/images using form data in&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":3273,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[173],"tags":[79,62,150,145],"class_list":["post-2374","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-react-native","tag-android","tag-php","tag-react-native","tag-source-code"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.bagi2info.com\/en\/wp-json\/wp\/v2\/posts\/2374","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.bagi2info.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bagi2info.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bagi2info.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bagi2info.com\/en\/wp-json\/wp\/v2\/comments?post=2374"}],"version-history":[{"count":10,"href":"https:\/\/www.bagi2info.com\/en\/wp-json\/wp\/v2\/posts\/2374\/revisions"}],"predecessor-version":[{"id":3630,"href":"https:\/\/www.bagi2info.com\/en\/wp-json\/wp\/v2\/posts\/2374\/revisions\/3630"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bagi2info.com\/en\/wp-json\/wp\/v2\/media\/3273"}],"wp:attachment":[{"href":"https:\/\/www.bagi2info.com\/en\/wp-json\/wp\/v2\/media?parent=2374"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bagi2info.com\/en\/wp-json\/wp\/v2\/categories?post=2374"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bagi2info.com\/en\/wp-json\/wp\/v2\/tags?post=2374"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}