首页 > 解决方案 > 如何通过放大、反应原生应用程序将 base64 图像上传到 S3

问题描述

寻找一个如何使用放大将 base64 图像上传到 aws S3 的简单示例。

标签: imagereact-nativebase64aws-amplify

解决方案


假设您配置了 Amplify Storage 并将权限设置为 public,下面是一个使用 Amplify 的 Storage 将图像上传到 S3 存储桶的代码示例。使用 Expo 的 ImagePicker 从本地设备获取图像。

import React from 'react';
import { 
  StyleSheet, 
  ScrollView, 
  Image, 
  Dimensions } from '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'

class App extends React.Component {
 state = {
 image: null,
 }

 // fetch a single image from user's device and save it to S3
 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)
  }
 }

 // add a single image to S3
 uploadImage = async uri => {
  const response = await fetch(uri)
  const blob = await response.blob() // format the data for images 
  const folder = 'images'
  const fileName = 'flower.jpeg'
  await Storage.put(folder + '/' + 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}
      />
      {/*
        true && expression always evaluates to expression, 
        and false && expression always evaluates to false 
      */}
      {image &&
        <Image source={{ uri: image }} style={{ width: width, height: height/2 }} />
      }

    </ScrollView>   
  );
 }
}

图像的名称是硬编码的,这不好。但这仍然是一个非常好的开始。


推荐阅读