Last active
February 25, 2022 15:42
-
-
Save aofleejay/4ce76618b0ff807723e4ed5244226253 to your computer and use it in GitHub Desktop.
Reduce size of images and videos before upload to server using react-native-image-picker. ref: https://github.com/react-native-image-picker/react-native-image-picker#options
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {useState} from 'react'; | |
import {Pressable, Text, View} from 'react-native'; | |
import {launchImageLibrary} from 'react-native-image-picker'; | |
import RNFetchBlob from 'rn-fetch-blob'; | |
const App = () => { | |
const [selectedAssets, setSelectedAssets] = useState([]); | |
const selectAssets = async () => { | |
const response = await launchImageLibrary({ | |
mediaType: 'mixed', | |
includeExtra: true, | |
selectionLimit: 10, | |
// Resize assets to reduce data tranfer | |
// For images | |
maxWidth: 1080, | |
maxHeight: 1080, | |
quality: 0.5, | |
// For videos | |
videoQuality: 'low', | |
}); | |
console.log(JSON.stringify(response.assets, null, 2)); | |
setSelectedAssets(response.assets); | |
}; | |
const uploadAssets = async () => { | |
try { | |
const startTime = performance.now(); | |
const uploadAssetsQueue = []; | |
selectedAssets.forEach(asset => { | |
uploadAssetsQueue.push( | |
RNFetchBlob.fetch( | |
'POST', | |
'http://localhost:4000/objects', | |
{ | |
'Content-Type': asset.type, | |
'Content-Disposition': `attachment; filename="${asset.fileName}"`, | |
}, | |
RNFetchBlob.wrap( | |
decodeURIComponent(asset.uri.replace('file:/', '')), | |
), | |
), | |
); | |
}); | |
const response = await Promise.all(uploadAssetsQueue); | |
console.log(performance.now() - startTime); | |
console.log(response); | |
} catch (error) { | |
console.log(error.message); | |
} | |
}; | |
return ( | |
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> | |
<Pressable onPress={selectAssets}> | |
<Text>Choose Images</Text> | |
</Pressable> | |
<Pressable onPress={uploadAssets}> | |
<Text>Upload Images</Text> | |
</Pressable> | |
</View> | |
); | |
}; | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment