我想为这个问题添加一个更完整的答案。
下面的代码允许使用来自 Expo 的ImagePicker从移动设备库中挑选图像,并使用来自AWS Amplify的Storage将图像存储在 S3 中。
import React from 'react';
import { StyleSheet, ScrollView, Image, Dimensions } from 'react-native'
import { withAuthenticator } from 'aws-amplify-react-native'
import { ImagePicker, Permissions } from 'expo'
import { Icon } from 'native-base'
import Amplify from '@aws-amplify/core'
import Storage from '@aws-amplify/storage'
import config from './aws-exports'
Amplify.configure(config)
class App extends React.Component {
state = {
image: null,
}
// permission to access the user's phone library
askPermissionsAsync = async () => {
await Permissions.askAsync(Permissions.CAMERA_ROLL);
}
useLibraryHandler = async () => {
await this.askPermissionsAsync()
let result = await ImagePicker.launchImageLibraryAsync(
{
allowsEditing: false,
aspect: [4, 3],
}
)
console.log(result);
if (!result.cancelled) {
this.setState({ image: result.uri })
this.uploadImage(this.state.image)
}
}
uploadImage = async uri => {
const response = await fetch(uri);
const blob = await response.blob();
const fileName = 'dog77.jpeg';
await Storage.put(fileName, blob, {
contentType: 'image/jpeg',
level: 'public'
}).then(data => console.log(data))
.catch(err => console.log(err))
}
render() {
let { image } = this.state
let {height, width} = Dimensions.get('window')
return (
<ScrollView style={{flex: 1}} contentContainerStyle={styles.container}>
<Icon
name='md-add-circle'
style={styles.buttonStyle}
onPress={this.useLibraryHandler}
/>
{image &&
<Image source={{ uri: image }} style={{ width: width, height: height/2 }} />
}
</ScrollView>
);
}
}
export default withAuthenticator(App, { includeGreetings: true })
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
buttonStyle: {
fontSize: 45,
color: '#4286f4'
}
});