Search code examples
reactjsamazon-s3wysiwygrte

Temporarily upload on S3 and remove if it's not used?


I'm trying to implement wysiwyg text editor on react using react-draft-wysiwyg.

For uploading image using the text editor, i'm trying to post the file on uploadCallback function to S3 and return the url for the uploaded item to the editor.

But I don't know how to handle unused image (deleted before submit) that s just hanging around in my S3 bucket. Is there any good method to prevent this? I was trying to just post the image in base64 format but that seems just way to much and waste of memory.


Solution

  • There are a couple of ways you can solve this:

    Obtain Pre-signed URL from a Lambda

    You can write a lambda function behind an API Gateway that you could call to give you pre-signed URL to post on S3. This URL will allow anyone that has this URL to upload one time to S3. When the user is ready to submit the text-editor, you would just post the attached file to S3 using the pre-signed URL.

    C# Lambda Example

    IAmazonS3 client;
    client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);
    // Generate a pre-signed URL.
    GetPreSignedUrlRequest request = new GetPreSignedUrlRequest
       {
           BucketName = bucketName,
            Key        = objectKey,
            Verb       = HttpVerb.PUT,
            Expires    = DateTime.Now.AddMinutes(5)
        };
    string url = null;
     url = s3Client.GetPreSignedURL(request);
    
    // Upload a file using the pre-signed URL.
    HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest;
    httpRequest.Method = "PUT";
    using (Stream dataStream = httpRequest.GetRequestStream())
    {
       // Upload object.
    }
    
    HttpWebResponse response = httpRequest.GetResponse() as HttpWebResponse;
    

    You can find more examples at AWS S3s documentation on obtaining a pre-signed URL via a Lambda written in Java, C#, Ruby, etc..

    For doing the upload to a pre-signed URL from your Reactjs app, you can find some awesome examples at this Stackoverflow post.

    S3 Object Expiration

    You can move all pending images to a bucket that has its lifecycle configured to delete objects within a certain period. Then, when the post is submitted, you can move the object from the transitory bucket to a more permanent bucket. More information on S3 object expiration can be found in their docs.