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,
});
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.
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 (.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With