Naman Jain
Naman Jain

Reputation: 1

I need to implement a file upload feature so that any user could upload a file in AWS S3 bucket from frontend. My project is in Typescript Language

I have achieved it by using the AWS credentials embedded in the code. But this is not good practice ..could someone suggest another way to do that maybe by using IAM role or assume role.

Code for receiving the file from frontend

<Grid item xs={12} className={classes.field}>
        <Typography variant="h6">
            6. If File Not Present In S3 buket then First Upload The File In S3
          </Typography>
            <DropzoneArea
              acceptedFiles={['.csv']}
              //acceptedFiles={['image/*']}
              dropzoneText={"Drag and drop an .csv file here"}
              dropzoneClass={classes.dropZone}
              useChipsForPreview={true}
              filesLimit={1}
              ////maxFileSize={200000}
              //fileObjects=fileObjects
              onChange={(files) =>  setFileList(files)} 
            />
            <Button
                size="large"
                type="submit"
                color="primary"
                variant="contained"
                endIcon={<FiUpload />}
                onClick={handleFileUploadSubmit}
              >
                Upload File In S3
              </Button>
          </Grid>

Passing the file object and further below is the code for uploading the file in AWS using credentials embeeded in code-

import S3 from 'react-aws-s3';
import {
    errorAlertWithoutTimer,
    successAlert,
  } from '../../sweetAlerts/SweetAlerts'
window.Buffer = window.Buffer || require("buffer").Buffer;

const config = {
    bucketName: '',
    region: '',
    accessKeyId: '',
    secretAccessKey: '',
    s3Url: '',
}





export const  uploadFileInAws= (file: any) => {
    const ReactS3Client = new S3(config);
    console.log(file,file.name)
    ReactS3Client
    .uploadFile(file, file.name)
    .then(successAlert('Success', 'File Upload SuccessFully Queued'))
    .catch(err => console.error(err))

  }

Upvotes: 0

Views: 465

Answers (1)

stephenisau
stephenisau

Reputation: 66

You probably want to access the variables through the process.env variables.

Since this is on the client-side and assuming you're just using a bootstrapped CRA app (and not a barebones babel + webpack (or other) config), you can access the variables through a .env file.

This link is a good example.

Hope this helps!

Upvotes: 0

Related Questions