Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I POST or PUT raw binary using react native

I need to PUT an image file from the react native app to an pre-configured s3 upload URL. I saw an example with fetch that uploads the image as a binary via path, but it does so as a multi-part form upload. Because the s3 upload url can only take it as a raw binary in the body - and not as a content-type of multi-part, what's the syntax to PUT the raw binary image as the body using fetch or any other library in react native?

The following code uploads it as form data - which is not what I want to do.

          var photo = {
            uri: response.uri,
            name: fileName,
          };
          const body = new FormData();  // how can I do this not as a form?
          body.append('photo', photo);
          const results = await fetch('https://somes3uploadurl.com, {
            method: 'PUT',
            body,
          });
like image 373
MonkeyBonkey Avatar asked Mar 23 '17 11:03

MonkeyBonkey


People also ask

How do you send binary data in react JS?

You can try to use FileReader to read the given file as binary and send it using fetch/axios. Second, the curl's -u "<account_sid>:<account_secret>" sends Authorization header. You can simply use btoa(username + ':' + 'password') to achieve that. Here's an example using fetch and FileReader.

What is a raw binary file?

rbf) Definition. A binary file (with the extension . rbf) containing configuration data for use outside the Quartus® Prime software. A Raw Binary File contains the binary equivalent of a Tabular Text File (.


1 Answers

It turns out you can send the file in multiple ways, including base64 and as a Buffer.

Using react-native-fs and buffer:

Uploading as base64 worked, but the image was damaged somehow. So i uploaded using a buffer:

export const uploadToAws = async (signedRequest, file) => {
  const base64 = await fs.readFile(file.uri, 'base64')
  const buffer = Buffer.from(base64, 'base64')
  return fetch(signedRequest, {
    method: 'PUT',
    headers: {
    'Content-Type': 'image/jpeg; charset=utf-8',
    'x-amz-acl': 'public-read',
   },
    body: buffer,
  })
}

Note that on the server, you need to make sure you are setting the correct Content-Type: { ContentType: "image/jpeg; charset=utf-8", 'x-amz-acl': 'public-read' } as it seems fetch adds the charset to Content-Type.

like image 141
Abdellah Alaoui Avatar answered Sep 29 '22 11:09

Abdellah Alaoui