Skip to content

Instantly share code, notes, and snippets.

@hyochan
Last active July 18, 2022 21:49
Show Gist options
  • Save hyochan/dee15792b2a308e37ff82c9a6c17b7fc to your computer and use it in GitHub Desktop.
Save hyochan/dee15792b2a308e37ff82c9a6c17b7fc to your computer and use it in GitHub Desktop.
expo image upload in both web and mobile
const fileName = uri.split('/').pop();
const fileType = mime.getType(uri);
const data: FormData = new FormData();
if (Platform.OS === 'web') {
const byteString = atob(uri.split(',')[1]);
const ab = new ArrayBuffer(byteString.length);
const arr = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++)
arr[i] = byteString.charCodeAt(i);
const blob = new Blob([arr], {
type: fileType || 'image/png',
});
const file = new File([blob], `${fileName}${fileNamePrefix}`);
data.append('inputFile', file);
} else
data.append('inputFile', {
uri,
type: fileType || 'image/png',
name: `${fileName}${fileNamePrefix}`,
});
const fetchOption = {
method: 'POST',
body: data,
headers: Platform.select({
web: {
Accept: 'application/json',
Authorization: `Bearer ${token}`,
},
default: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${token}`,
},
}),
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment