Using AWS S3 and Lambda for File Uploads in React Native ๐ฒ
Codenova
Blockchain & Web Development Company
When building apps, efficient file uploads are essential for a smooth user experience. Combining AWS S3 for storage and AWS Lambda for backend logic makes this simple and scalable. Hereโs how to implement file uploads in a React Native app.
Prerequisites
- AWS Account: Sign up here.
- React Native project set up (you can use
npx react-native initto start one). - Node.js and npm installed.
Step 1: Set Up Your S3 Bucket ๐ฆ
- Log into AWS and go to S3.
- Create a New Bucket:Click Create Bucket and give it a unique name.Select your region and leave the other settings at default.
- Set Permissions:Go to Permissions and ensure itโs private.Later, youโll provide access to upload files via AWS Lambda.
Step 2: Create the Lambda Function ๐
AWS Lambda will handle the upload authorization.
- Go to AWS Lambda and select Create Function.Choose Author from scratch.Name the function (e.g.,
reactNativeFileUpload).Set the Runtime to Node.js. - Write the Function Code:Add the following code to generate a pre-signed S3 URL, allowing the app to upload files securely.
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
exports.handler = async (event) => {
const bucketName = 'YOUR_BUCKET_NAME';
const fileName = event.queryStringParameters.fileName;
const params = {
Bucket: bucketName,
Key: fileName,
Expires: 60, // URL expiration time in seconds
ContentType: 'application/octet-stream',
};
try {
const uploadURL = await s3.getSignedUrlPromise('putObject', params);
return {
statusCode: 200,
body: JSON.stringify({ uploadURL }),
};
} catch (error) {
return {
statusCode: 500,
body: JSON.stringify({ error: 'Failed to create upload URL' }),
};
}
};
3. Environment Variables:Set your Bucket name in the code or use Lambda environment variables.
4. Add Permissions:Attach the S3 permissions to allow access to your bucket by going to the Lambda role in IAM and adding the AmazonS3FullAccess policy.
Step 3: Create an API Gateway ๐
Now, create an API Gateway to make the Lambda function accessible to your app.
- Go to API Gateway and select Create API.
- Choose REST API and configure the settings.
- Create a New Resource with a path like
/get-upload-url. - Link to Lambda:Set up a GET method on this resource.Select Lambda Function as the integration type, and choose your Lambda function.
- Deploy the API:Go to Deploy API, create a new stage (e.g.,
dev), and note the Invoke URL. This will be used in the React Native app.
Step 4: Connect React Native App to API Gateway ๐ฑ
- Install Axios:
npm install axios
2. Add the Upload Functionality: In your React Native code, import axios and define a function to upload files using the pre-signed URL.
import React, { useState } from 'react';
import { Button, View } from 'react-native';
import DocumentPicker from 'react-native-document-picker';
import axios from 'axios';
const YourComponent = () => {
const [file, setFile] = useState(null);
const pickFile = async () => {
try {
const res = await DocumentPicker.pick({
type: [DocumentPicker.types.allFiles],
});
setFile(res);
} catch (err) {
console.log('Error picking file:', err);
}
};
const uploadFile = async () => {
if (!file) return;
try {
// 1. Get pre-signed URL from Lambda function
const response = await axios.get(
'YOUR_API_GATEWAY_INVOKE_URL/get-upload-url',
{
params: { fileName: file.name },
}
);
const { uploadURL } = response.data;
// 2. Upload the file to S3
await axios.put(uploadURL, file, {
headers: {
'Content-Type': file.type,
},
});
alert('File uploaded successfully!');
} catch (error) {
console.log('File upload error:', error);
alert('Failed to upload file.');
}
};
return (
<View>
<Button title="Pick File" onPress={pickFile} />
<Button title="Upload File" onPress={uploadFile} />
</View>
);
};
export default YourComponent;
Step 5: Test Your File Upload ๐
- Run your app and use the Pick File button to select a file.
- Then click Upload File to upload the file to AWS S3.
- You should see a success message, and the file will appear in your S3 bucket.
Conclusion
Using AWS S3 and Lambda for file uploads provides a scalable and secure way to manage file storage in React Native apps. This method helps offload processing to AWS, keeps your app responsive, and makes handling large files easy.
