리액트 네이티브에서 Parse SDK로 파일 저장 및 읽기
12 분
리액트 네이티브 앱에서 파일 저장하기 소개 이 가이드에서는 parse javascript sdk를 사용하여 back4app 클라우드 저장소에서 파일을 저장하고 검색하는 방법을 배웁니다 parse 세계에서는 파일을 관리하기 위해 \<font color="#2166ae">parse file\</font> 유형을 사용합니다 \<font color="#2166ae">parse file\</font> 을 생성한 후, \<font color="#2166ae">save()\</font> 메서드를 사용하여 back4app 클라우드에 저장합니다 파일을 다른 데이터 객체와 항상 연결해야 이 파일 경로를 객체를 쿼리할 때 검색할 수 있습니다 연결하지 않으면 파일은 저장되지만 클라우드에서 찾을 수 없습니다 또 다른 중요한 팁은 파일 확장자가 있는 이름을 파일에 부여하는 것입니다 이 확장자는 parse가 파일 유형을 파악하고 적절하게 처리할 수 있도록 합니다 또한 각 업로드는 고유 식별자를 가지므로 동일한 이름을 사용하여 여러 파일을 업로드하는 데 문제가 없습니다 리액트 네이티브 앱의 가장 일반적인 사용 사례는 이미지를 저장하는 것입니다 이 가이드에서는 사진을 저장하고 표시하는 데모 갤러리 앱을 구축합니다 이 튜토리얼에서 생성된 앱의 전체 샘플 코드는 여기 https //github com/templates back4app/react native demo gallery app 단계별로 따라 하거나 코드로 바로 이동하셔도 됩니다 이미지 재생 파일을 데이터 객체에 연결하지 않으면 파일은 고아 파일이 되어 back4app 클라우드에서 찾을 수 없습니다 목표 parse javascript와 back4app을 사용하여 이미지를 업로드하고 표시하는 리액트 네이티브 갤러리 앱을 만드는 것입니다 전제 조건 이 튜토리얼을 완료하려면 다음이 필요합니다 parse sdk 설치 https //www back4app com/docs/parse sdk/react native sdk 튜토리얼을 완료하세요 1 의존성 설치 react native 앱에서 파일(즉, 사진 업로드) 작업은 가장 일반적인 기능 중 하나입니다 이 튜토리얼에서는 이미지를 업로드하고 표시하는 간단한 갤러리 앱을 구축할 것입니다 react native 프로젝트가 back4app과 성공적으로 연결된 https //www back4app com/docs/parse sdk/react native sdk , 루트 디렉토리로 이동하여 다음 종속성을 설치하세요 cd startwithback4app \# 장치에서 이미지를 선택하려면 yarn add react native image picker ios의 경우, pods를 설치하세요 cd ios && npx pod install react native \<font color="#2166ae">v0 60+\</font> 에 대해 자동 연결이 가능하지만, \<font color="#2166ae">react native image picker\</font> 의 이전 버전 설치에 대한 정보는, 여기에서 공식 문서를 확인하세요 https //github com/react native image picker/react native image picker 설치 후, 사용자가 ios의 사진에서 이미지/비디오를 선택할 수 있도록 \<font color="#2166ae">nsphotolibraryusagedescription\</font> 키를 \<font color="#2166ae">info plist\</font> 에 추가해야 합니다 \<dict> //other keys \<key>nsphotolibraryusagedescription\</key> \<string>여기 app name here가 귀하의 사진에 접근하고자 합니다\</string> \</dict> 안드로이드에서는 갤러리에서 사진을 선택하기 위해 권한이 필요하지 않습니다 2 갤러리에서 이미지 선택하기 다음으로, 갤러리에서 이미지를 선택하고 업로드하는 ui와 로직을 감싸는 컴포넌트를 구축할 것입니다 루트 디렉토리에서 다음 내용을 가진 \<font color="#2166ae">uploadingimage js\</font> 파일을 생성하세요 1 import react, {usestate} from 'react'; 2 import {view, button, image, stylesheet} from 'react native'; 3	 4 import {launchimagelibrary} from 'react native image picker'; 5 import parse from 'parse/react native js'; 6	 7 const uploadimage = () => { 8 const \[image, setimage] = usestate(null); 9	 10 async function upload() { 11 // todo implement this method 12 } 13 // this will open phone image library 14 function pickimage() { 15 launchimagelibrary( 16 { 17 mediatype 'photo', 18 includebase64 true, 19 maxheight 200, 20 maxwidth 200, 21 }, 22 (response) => { 23 // add selected image to the state 24 setimage(response); 25 }, 26 ); 27 } 28	 29 return ( 30 \<view> 31 \<button 32 onpress={pickimage} 33 title="pick an image from gallery" 34 color="#841584" /> 35 {image && \<image source={ {uri image uri} } style={styles currentimage}/>} 36	 37 {image && \<button title="upload" color="green" onpress={upload} />} 38 \</view> 39 ); 40	 41 }; 42	 43 const styles = stylesheet create({ 44 container { 45 height 400, 46 justifycontent 'center', 47 alignitems 'center', 48 }, 49 currentimage { 50 width 250, 51 height 250, 52 resizemode 'cover', 53 alignself 'center', 54 }, 55 }); 56	 57 export default uploadimage; 위의 구성 요소는 다음과 같이 렌더링됩니다 사용자가 클릭할 때 이미지 라이브러리를 여는 버튼 선택된 이미지와 업로드 버튼 보시다시피, \<font color="#2166ae">업로드\</font> 메서드는 아무것도 하지 않습니다 다음으로, 그 동작을 구현하고 실제로 이미지를 back4app 클라우드에 업로드하는 방법을 살펴보겠습니다 3 이미지 업로드 back4app 스토리지는 \<font color="#2166ae">parse file\</font> 을 기반으로 하며 문서, 이미지, 비디오, 음악 및 기타 이진 데이터를 저장할 수 있습니다 \<font color="#2166ae">parse file\</font> 은 파일 저장 프로세스를 추상화하고 쉽게 사용할 수 있도록 parse javascript sdk에서 제공하는 유틸리티 클래스입니다 따라서 이미지를 업로드하려면 \<font color="#2166ae">parse file\</font> 인스턴스를 생성한 다음 save 메서드를 호출하면 됩니다 이렇게 하면 parse가 나머지를 자동으로 처리합니다 parse 파일에 대한 전체 문서는 여기에서 확인할 수 있습니다 https //docs parseplatform org/js/guide/#files 이제 \<font color="#2166ae">업로드\</font> 함수에서 이를 수행해 보겠습니다 1 async function upload() { 2 // 1 create a file 3 const {base64, filename} = image; 4 const parsefile = new parse file(filename, {base64}); 5	 6 // 2 save the file 7 try { 8 const responsefile = await parsefile save(); 9 const gallery = parse object extend('gallery'); 10 const gallery = new gallery(); 11 gallery set('picture', responsefile); 12	 13 await gallery save(); 14 alert alert('the file has been saved to back4app '); 15 } catch (error) { 16 console log( 17 'the file either could not be read, or could not be saved to back4app ', 18 ); 19 } 20 } 요약하자면, 위의 코드 조각은 선택한 이미지를 생성하고 저장하며, 저장이 완료된 후 \<font color="#2166ae">parse object\</font> 와 연결합니다 \<font color="#2166ae">gallery\</font> 이제 \<font color="#2166ae">uploadimage\</font> 컴포넌트를 \<font color="#2166ae">app js\</font> 에서 가져와 사용해야 합니다 1 import react from 'react'; 2 import {safeareaview, stylesheet} from 'react native'; 3 // in a react native application 4 import parse from 'parse/react native js'; 5 import asyncstorage from '@react native community/async storage'; 6 import keys from ' /constants/keys'; 7 //before using the sdk 8 parse setasyncstorage(asyncstorage); 9 parse initialize(keys applicationid, keys javascriptkey); 10 parse serverurl = keys serverurl; 11	 12 import uploadimage from ' /uploadimage'; 13	 14 const app = () => { 15 return ( 16 \<safeareaview style={styles container}> 17 \<uploadimage/> 18 \</safeareaview> 19 ) 20 }; 21	 22 const styles = stylesheet create({ 23 container { 24 backgroundcolor '#f5f5f5', 25 flex 1, 26 }, 27 title { 28 fontsize 18, 29 textalign 'center', 30 fontweight 'bold', 31 }, 32 }); 33	 34 export default app; 그렇게 하면 갤러리에서 이미지를 선택할 수 있어야 합니다 그리고 업로드 버튼을 눌러 이미지를 성공적으로 업로드합니다 4 이미지 표시하기 이미지의 내용을 가져오고 사용자에게 표시하기 위해 이미지의 url을 가져와야 합니다 다음으로, \<font color="#2166ae">갤러리\</font> 객체에서 이미지를 쿼리하고 flatlist에 표시하는 컴포넌트를 만들 것입니다 루트 디렉토리에서 다음 내용을 가진 \<font color="#2166ae">gallery js\</font> 파일을 생성하세요 1 import react, {usestate, useeffect} from 'react'; 2 import {text, image, flatlist, stylesheet} from 'react native'; 3	 4 import parse from 'parse/react native js'; 5	 6 const gallery = () => { 7 const \[images, setimages] = usestate(\[]); 8	 9 useeffect(() => { 10 const fetchimages = async () => { 11 let query = new parse query('gallery'); 12 const results = await query find(); 13 setimages(results); 14 }; 15 16 fetchimages(); 17 }, \[]); 18	 19 return ( 20 \<flatlist 21 style={styles container} 22 contentcontainerstyle={styles listcontent} 23 data={images} 24 horizontal={false} 25 numcolumns={3} 26 listemptycomponent={() => \<text>no images uploaded \</text>} 27 renderitem={({item}) => 28 \<image source={ {uri item get('picture') url()} } style={styles imageitem}/> 29 )} 30 keyextractor={(item) => item id} 31 />); 32 }; 33	 34 const styles = stylesheet create({ 35 container { 36 flex 1, 37 backgroundcolor '#f5f5f5', 38 }, 39 listcontent { 40 justifycontent 'center', 41 alignitems 'center', 42 }, 43 imageitem { 44 width 100, 45 height 100, 46 resizemode 'cover', 47 marginhorizontal 5, 48 marginvertical 5, 49 }, 50 }); 51	 52 export default gallery; 위의 구성 요소는 \<font color="#2166ae">useeffect\</font> 훅을 사용하여 렌더링이 완료되면 \<font color="#2166ae">gallery\</font> 객체에 업로드된 이미지를 쿼리합니다 다음으로, 이 구성 요소를 \<font color="#2166ae">app js\</font> 1 // other imports 2 import uploadimage from ' /uploadimage'; 3 import gallery from ' /gallery'; 4	 5 const app = () => { 6 return ( 7 \<safeareaview style={styles container}> 8 \<uploadimage/> 9 \<gallery/> 10 \</safeareaview> 11 ); 12 } 앱을 실행하면 업로드된 이미지 목록을 다음과 같이 볼 수 있어야 합니다 5 완료되었습니다! 이 시점에서 back4app에 첫 번째 이미지를 업로드하고 react native 애플리케이션에 표시했습니다