---
title: 리액트 네이티브에서 Parse SDK로 파일 저장 및 읽기
slug: docs-kr/react-native/parse-sdk/working-with-files/react-native-save-file
description: 리액트 네이티브 앱에서 Back4App에 파일을 저장하고 읽는 방법을 알아보세요.
image: https://www.back4app.com/images/logo-social.png
createdAt: 2024-03-19T17:15:39.852Z
---

# 리액트 네이티브 앱에서 파일 저장하기

## 소개

이 가이드에서는 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). 단계별로 따라 하거나 코드로 바로 이동하셔도 됩니다.
이미지 재생.

:::hint{type="danger"}
파일을 데이터 객체에 연결하지 않으면 파일은 고아 파일이 되어 Back4App 클라우드에서 찾을 수 없습니다.
:::

## 목표

Parse Javascript와 Back4app을 사용하여 이미지를 업로드하고 표시하는 리액트 네이티브 갤러리 앱을 만드는 것입니다.

## 전제 조건

:::hint{type="info"}
**이 튜토리얼을 완료하려면 다음이 필요합니다:**

- &#x20;[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), 루트 디렉토리로 이동하여 다음 종속성을 설치하세요:

:::BlockQuote
cd startWithBack4app

\# 장치에서 이미지를 선택하려면
yarn add react-native-image-picker&#x20;
:::

iOS의 경우, pods를 설치하세요:

:::BlockQuote
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>에 추가해야 합니다.

:::BlockQuote
\<dict>
//other keys ...
\<key>NSPhotoLibraryUsageDescription\</key>
\<string>여기 APP\_NAME\_HERE가 귀하의 사진에 접근하고자 합니다\</string>&#x20;
\</dict>
:::

안드로이드에서는 갤러리에서 사진을 선택하기 위해 권한이 필요하지 않습니다.

## 2 - 갤러리에서 이미지 선택하기

다음으로, 갤러리에서 이미지를 선택하고 업로드하는 UI와 로직을 감싸는 컴포넌트를 구축할 것입니다.

루트 디렉토리에서 다음 내용을 가진 <font color="#2166ae">`UploadingImage.js`</font> 파일을 생성하세요:

```javascript
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;
```

위의 구성 요소는 다음과 같이 렌더링됩니다:

1. 사용자가 클릭할 때 이미지 라이브러리를 여는 버튼
2. 선택된 이미지와 업로드 버튼

보시다시피, <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> 함수에서 이를 수행해 보겠습니다:

```javascript
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>에서 가져와 사용해야 합니다:

```javascript
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;
```

그렇게 하면 갤러리에서 이미지를 선택할 수 있어야 합니다:

::Image[]{src="https://api.archbee.com/api/optimize/yD3zCY-NNBBIfd0uqcfR5/wj-9xLb7nlPZOFo-Z3n_J_image.png" size="50" width="380" height="796" position="center" showCaption="false"}

그리고 업로드 버튼을 눌러 이미지를 성공적으로 업로드합니다:

::Image[]{src="https://api.archbee.com/api/optimize/yD3zCY-NNBBIfd0uqcfR5/kosbv459hnKX83Q1F8Uo7_image.png" size="50" width="377" height="797" position="center" showCaption="false"}

## 4 - 이미지 표시하기

이미지의 내용을 가져오고 사용자에게 표시하기 위해 이미지의 URL을 가져와야 합니다. 다음으로, <font color="#2166ae">`갤러리`</font> 객체에서 이미지를 쿼리하고 FlatList에 표시하는 컴포넌트를 만들 것입니다.

루트 디렉토리에서 다음 내용을 가진 <font color="#2166ae">`Gallery.js`</font> 파일을 생성하세요:

```javascript
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>:

```javascript
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	}
```

앱을 실행하면 업로드된 이미지 목록을 다음과 같이 볼 수 있어야 합니다:

::Image[]{src="https://api.archbee.com/api/optimize/yD3zCY-NNBBIfd0uqcfR5/qWi5YHa87nR0gLTJ4Rsdh_image.png" size="50" width="377" height="799" position="center" showCaption="false"}

## 5 - 완료되었습니다!

이 시점에서 Back4App에 첫 번째 이미지를 업로드하고 React Native 애플리케이션에 표시했습니다.
