Skip to content

Instantly share code, notes, and snippets.

@EQuimper
Last active May 25, 2021 14:38
Show Gist options
  • Save EQuimper/90fba31f9d0ecb8f6926709a4dbc46d2 to your computer and use it in GitHub Desktop.
Save EQuimper/90fba31f9d0ecb8f6926709a4dbc46d2 to your computer and use it in GitHub Desktop.
Upload a image using presign url from s3 in React-Native
export async function uploadImage(method: string, url: string, file: any) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open(method, url)
xhr.setRequestHeader('Content-Type', file.type)
xhr.onload = () => {
if (xhr.status !== 200) {
reject(
new Error(
`Request failed. Status: ${xhr.status}. Content: ${xhr.responseText}`
)
)
}
resolve(xhr.responseText)
}
xhr.send(file)
})
}
@MayoudP
Copy link

MayoudP commented Jul 7, 2020

I'm doing it like this :

  function formData(data, file) {
    var res = new FormData();
    for (var k in data) {
      res.append(k, data[k]);
    }
    res.append('file', { uri, name: fileName, type })
    return res;
  }

  const xhr = new XMLHttpRequest()
  xhr.open('POST', url)
  xhr.setRequestHeader('Content-Type', meta.type)
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        // Successfully uploaded the file.
        console.log('successfully uploaded presignedurl');
        console.log(xhr);
      } else {
        // The file could not be uploaded.
        console.log('failed to upload presignedurl');
        console.log(xhr);
      }
    }
  };
  xhr.send(formData(fields, file));

But I'm keep getting this error

<Error>
       <Code>EntityTooLarge</Code>
       <Message>Your proposed upload exceeds the maximum allowed size</Message>
       <ProposedSize>18190</ProposedSize>
       <MaxSizeAllowed>15670</MaxSizeAllowed>
</Error

seems to be related to local size and actual upload size of the file which is modified, god know why, RN bug... Do you have any ideas about how to fixe it ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment