Skip to content

Instantly share code, notes, and snippets.

@hungdev
Created September 11, 2021 16:43
Show Gist options
  • Save hungdev/26cfd6f3f1182bab9325672bb7ea47f4 to your computer and use it in GitHub Desktop.
Save hungdev/26cfd6f3f1182bab9325672bb7ea47f4 to your computer and use it in GitHub Desktop.
react native s3 upload
import { Platform, StyleSheet } from 'react-native';
import fs from 'react-native-fs';
import { decode } from 'base64-arraybuffer';
import AWS from 'aws-sdk';
import 'react-native-get-random-values'
import { customAlphabet } from 'nanoid'

const nanoid = customAlphabet('1234567890abcdef', 10)

export const uploadFileToS3 = async (files) => {
  const BUCKET_NAME = 'Your bucket name';
  const IAM_USER_KEY = 'your key';
  const IAM_USER_SECRET = 'your access key secret';

  const s3bucket = new AWS.S3({
    accessKeyId: IAM_USER_KEY,
    secretAccessKey: IAM_USER_SECRET,
    Bucket: BUCKET_NAME,
    signatureVersion: 'v4',
  });

  let tasks = []

  for (let i in files) {
    const contentType = files[i].type;
    const contentDeposition = `inline;filename="${files?.[i]?.fileName}"`;
    const fPath = Platform.OS === 'ios' ? files?.[i].path.replace('file://', '') : files?.[i].path;

    const base64 = await fs.readFile(fPath, 'base64');

    const arrayBuffer = decode(base64);

    const fileNameSplit = (files?.[i]?.fileName || files?.[i]?.filename)?.split('.')

    tasks.push(new Promise((resolve, reject) => {
      s3bucket.createBucket(() => {
        const params = {
          Bucket: BUCKET_NAME,
          Key: (fileNameSplit?.[0] + '-' + nanoid() + '.' + fileNameSplit?.[1]),
          Body: arrayBuffer,
          ContentDisposition: contentDeposition,
          ContentType: contentType,
        };
        s3bucket.upload(params, (error, data) => {
          if (error) {
            reject(error);
          } else {
            resolve(data);
          }
        });
      });
    }))

  }

  return await Promise.all(tasks)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment