React Native Expo Image Upload to Rails Api
It is very common to allow a user to upload a photo in a given application and tin can brand an application more dynamic and interactive. Today we are going to talk about how to allow a user to upload an image to Cloudinary using Cloudinary's API and how to retrieve that epitome from Cloudinary. When trying to include Cloudinary in my awarding, I was running into problems with Cloudinary not accepting the file uploaded from Expo. I could non find very much helpful documentation on line so I'thou hoping this tutorial will help others who run into the same issue every bit I did.
The first matter you will want todo is install Expo'south ImagePicker. You lot can exercise this by entering the following code into your final.
expo install expo-image-picker
In any file that yous wish to allow a user to upload a file, you will need to import ImagePicker at the top.
import * as ImagePicker from 'expo-image-picker';
Side by side we will write a part. Virtually of this code tin can be found in Expo's docks but I take included some extra lawmaking. The file blazon that image picker normal supplies is non the right format for Cloudinary then I had to modify Expo'south code a petty bit so that Cloudinary would accept the file.
I started with declaring a variable to contain the url for Cloudinary'south API.
In the Cloudinary Dashboard the first line is your cloudinary name. You will want to insert that into the cloudinayry url as seen in the code snippet below the cloudinary image. You do not demand the curly brackets around your cloudinary name.
allow CLOUDINARY_URL = 'https://api.cloudinary.com/v1_1/{insert your cloudinary name here}/upload';
When using the Cloudinary API we don't need to use the API key, surreptitious or surround variable. You will need an upload preset. Go to your Cloudinary Dashboard. Go to Settings. Once you are on your settings page, become to the "upload" tab. Gyre downwards to "upload presets". You will need to change the settings to "unsigned". This will so supply you with the upload preset that you need. You tin either create a variable for it like we did for the cloudinary url but in my example I plugged it straight inside the function.
Now permit's write the role! I will provide seudo code for each line explaining what each part does.
//allows user to upload a photograph //asks phone for permission to admission photos allow openImagePickerAsync = async () => { let permissionResult = await ImagePicker.requestCameraRollPermissionsAsync(); //this tells the application to give an warning if someone doesn't allow //permission. It volition render to the previous screen. if (permissionResult.granted === false) { alert('Permission to access camera roll is required!'); render; } //This gets image from phone let pickerResult = await ImagePicker.launchImageLibraryAsync({ allowsEditing: true, aspect: [4, 3], //We demand the prototype to exist base64 in society to exist formatted for Cloudinary base64: true }); //this just returns the user to the previous page if they click "cancel" if (pickerResult.cancelled === true) { return; } //sets image from imagePicker to SelectedImage. //This is if yous are using hooks. The claw for this I have ready as: //[selectedImage, setSelectedImage] = useState(""). If you lot're using //anclass component you can use setState here. This file format will exist //a file path to where the epitome is saved. setSelectedImage({ localUri: pickerResult.uri }); //***Important*** This step is necessary. It converts image from //file path format that imagePicker creates, into a form that cloudinary //requires. let base64Img = `data:image/jpg;base64,${pickerResult.base64}`; // Here nosotros need to include your Cloudinary upload preset with tin can exist //found in your Cloudinary dashboard. let data = { "file": base64Img, "upload_preset": "insert your upload preset here,inside quotations", } //sends photo to cloudinary //**I initially tried using an axios request but it did Non work** I was //non able to go this to work until I changed it to a fetch asking. fetch(CLOUDINARY_URL, { body: JSON.stringify(data), headers: { 'content-type': 'application/json' }, method: 'POST', }).then(async r => { let data = await r.json() //Here I'm using another hook to set State for the photo that we go back //from Cloudinary setPhoto(data.url); }).take hold of(err => console.log(err)) }; We information we get back from Cloudinary will look similar to this. It can exist saved equally a string your database.
http://res.cloudinary.com/dary8ct/image/upload/v1580507361/fudyliwx7nxiezux561n.jpg To return the photograph in Expo, within your render section yous can include this:
return ( <Text> Look at our pretty picture show! </Text> <Image source={{ uri: "http://res.cloudinary.com/dary8ct/prototype/upload/v1580507361/fudyliwx7nxiezux561n.jpg" }} style={{ width: 150, height: 150 }} />} ) Below is the code without seudo lawmaking:
import React, { useState, useContext } from 'react'; import * equally ImagePicker from 'expo-epitome-picker'; export default function Photo(props) { let CLOUDINARY_URL = 'https://api.cloudinary.com/v1_1/{insert your cloudinary name here}/upload'; allow openImagePickerAsync = async () => { permit permissionResult = look ImagePicker.requestCameraRollPermissionsAsync(); if (permissionResult.granted === simulated) { warning('Permission to access camera roll is required!'); return; } let pickerResult = await ImagePicker.launchImageLibraryAsync({ allowsEditing: truthful, aspect: [iv, three], base64: true }); if (pickerResult.cancelled === true) { return; } setSelectedImage({ localUri: pickerResult.uri }); allow base64Img = `data:paradigm/jpg;base64,${pickerResult.base64}`; let data = { "file": base64Img, "upload_preset": "insert your upload preset here,within quotations", } fetch(CLOUDINARY_URL, { trunk: JSON.stringify(data), headers: { 'content-type': 'application/json' }, method: 'POST', }).then(async r => { let data = await r.json() setPhoto(data.url); }).catch(err => console.log(err)) }; return ( <View> <Text> Look at our pretty picture! </Text> <Image source={{ uri: "http://res.cloudinary.com/dary8ct/image/upload/v1580507361/fudyliwx7nxiezux561n.jpg" }} style={{ width: 150, height: 150 }} />} </View> ); } Hopefully this tutorial helped in allowing your awarding to upload photos to Cloudinary and display those images within your app!
johnstonfainterep.blogspot.com
Source: https://dev.to/joypalumbo/uploading-images-to-cloudinary-in-react-native-using-cloudinary-s-api-37mo
0 Response to "React Native Expo Image Upload to Rails Api"
Enviar um comentário