AWS S3 file upload - How to redirect on failure?

32 Views Asked by At

My application allows users to upload files to AWS S3 via a <form> using the AWS S3 REST API based on these AWS docs.

Here's some of the form code:

<form enctype="multipart/form-data" method="POST" class="aws-upload" action="http://civiform-local-s3-public.s3.localhost.localstack.cloud:4566/" id="image-file-upload-form">
  <input type="hidden" name="success_action_redirect" value="http://localhost:9000/admin/programs/58/image/file/EDIT">
  <!-- Lots of other inputs here -->
  <input type="file" name="file" class="usa-file-input__input" aria-describedby="file-input-hint-0 file-input-hint-1 " accept="image/jpeg,image/png" aria-label="Drag file here or choose from folder">
</form>

This all works great in the normal case: A user can upload a file, and then when the file is uploaded successfully they're redirected to the URL specified by the <input type="hidden" name="success_action_redirect" > element.

However, my application enforces a file size limit. If a user uploads a file that's too large, the AWS upload will fail with this error:

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
  <Code>EntityTooLarge</Code>
  <Message>Your proposed upload exceeds the maximum allowed size</Message>
  <ProposedSize>1052379</ProposedSize>
  <MaxSizeAllowed>1048576</MaxSizeAllowed>
  <RequestId>14NZFC9295TKNNFK</RequestId>
  <HostId>eFHrloKtxDZIpzHnMVUigFr1hLTFC++s50j/qOnW0BwX6rw4JOUV/5j5pKEuBBSEWZqRxSw6fV4=</HostId>
</Error>

I'm wondering how to more gracefully handle the failure case. At the bottom of those AWS docs, it says "If the POST request fails, Amazon S3 displays an error and does not provide a redirect.". This gives the user a bad experience, because they're taken away from my application and to a plaintext page that just displays the error:

Image of the plaintext page showing the error

If there was a POST request failure, I would instead like to redirect the user back to my application with some sort of helpful error message. Is there any way to do that using the AWS REST API? I haven't seen anything in the AWS docs but I'd be surprised if AWS doesn't provide a good way to handle failures.

I know that I can enforce the file size limit on the client-side, but I'd like to also handle the server-side error more gracefully as well.

0

There are 0 best solutions below