How to upload a base64 image to S3 with amplify, react native application - image

Looking for a simple example of how to upload a base64 image to aws S3 using amplify.

Assuming you configured Amplify Storage and set the permissions to public, here is a code example that uses Storage from Amplify to upload images to S3 bucket. The images are fetched from the local device using ImagePicker from Expo.
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>
);
}
}
The name of the image is hardcoded which is not good. But this is a very good start nonetheless.

This is a simple method for uploading multiple images. It should work for single image too.
import {Storage} from "aws-amplify";
UploadPhotos(SelectedImages) {
SelectedImages.forEach(async (element) => {
let name = element.filename;
let access = { level: "protected", contentType: "image/jpeg" };
let imageData = await fetch(element.uri);
let blobData = await imageData.blob();
try {
Storage.put(name, blobData, access);
} catch (err) {
console.log("UploadPhotos error: ", err);
}
});
}

Related

Next.js: Importing images into a component

I am using "next": "^9.4.4",
And have : "next-images": "^1.4.0", "next-optimized-images": "^2.6.1",
And this is my next-config.js
const withCSS = require('#zeit/next-css');
const withSass = require('#zeit/next-sass');
const withImages = require('next-images');
const optimizedImages = require('next-optimized-images');
module.exports = withImages(
optimizedImages(
withCSS(
withSass({
target: 'serverless',
env: {
MAPBOX_ACCESS_TOKEN:
'TK421'
},
webpack(config, options) {
config.module.rules.push({
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000,
target: 'serverless'
}
}
});
return config;
}
})
)
)
);
But in my component I get a broken image link, This is my component:
import { useState, useEffect } from 'react';
import { Card, Icon, Image, Segment, Form } from 'semantic-ui-react';
import axios from 'axios';
function ImageUploader({ userAvatar }) {
var [userAvatar, setUserAvatar] = useState(userAvatar);
useEffect(() => {
setUserAvatar(userAvatar);
}, [userAvatar]);
function fileUploader(e) {
console.log('event fileUploader ', e);
var imageFormObj = new FormData();
console.log('e.target.files[0] ', e.target.files[0]);
imageFormObj.append('imageName', 'multer-image-' + Date.now());
imageFormObj.append('imageData', e.target.files[0]);
setUserAvatar(window.URL.createObjectURL(e.target.files[0]));
console.log('userAvatar ', userAvatar);
console.log('imageFormObj ', imageFormObj);
axios
.post(`/users/uploadmulter`, imageFormObj)
.then(data => {
if (data.data.success) {
alert('Image has been successfully uploaded using multer');
}
})
.catch(err => {
alert('Error while uploading image using multer');
});
}
return (
<>
<Image
src={require('../../public/static/uploads/profile-avatars/placeholder.jpg')}
alt="user-avatar"
/>
</>
);
}
I am confused too because in the docs it seems to indicate static files/images are supported outta the box...
Static File Serving
Next.js can serve static files, like images, under a folder called public in the root directory. Files inside public can then be referenced by your code starting from the base URL (/).
For example, if you add an image to public/my-image.png, the following code will access the image:
I've tried as they recommend:
<Image src="/uploads/profile-avatars/placeholder.jpg" alt="user-avatar" />
And the funny thing I am not getting a 404 in the browser!
Any help would be appreciated!
Your image must be located in a folder with the reserved name public. Then the offer from the box will work.

Upload to S3 from React Native with AWS Amplify

I'm trying to upload an image to S3 from React Native using Amplify. I am able to upload a text file SUCCESSFULLY. But not an image.
Here is my code:
import React from 'react';
import {View, Text, Button, Image} from 'react-native';
import {identityPoolId, region, bucket} from '../auth';
import image from '../assets/background.png';
import Amplify, {Storage} from 'aws-amplify';
Amplify.configure({
Auth: {identityPoolId,region},
Storage : {bucket,region}
})
const upload = () => {
Storage.put('logo.jpg', image, {contentType: 'image/jpeg'})
.then(result => console.log('result from successful upload: ', result))
.catch(err => console.log('error uploading to s3:', err));
}
const get = () => { //this works for both putting and getting a text file
Storage.get('amir.txt')
.then(res => console.log('result get', res))
.catch(err => console.log('err getting', err))
}
export default function ImageUpload(props) {
return (
<View style={{alignItems : 'center'}}>
<Image style={{width: 100, height: 100}} source={image} />
<Text>Click button to upload above image to S3</Text>
<Button title="Upload to S3" onPress={upload}/>
<Button title="Get from S3" onPress={get}/>
</View>
)
}
the error message is:
error uploading to s3: [Error: Unsupported body payload number]
I ended up using the react-native-aws3 library to upload the images to S3.
I wish it could be more straight forward to find answers with how to upload an image directly using AWS amplify, but it wasn't working. So here is what I did:
(the wrapper of this function is a React Component. I'm using ImagePicker from 'expo-image-picker', Permissions from 'expo-permissions' and Constants from 'expo-constants' to set up the Image uploading from the Camera Roll)
import {identityPoolId, region, bucket, accessKey, secretKey} from '../auth';
import { RNS3 } from 'react-native-aws3';
async function s3Upload(uri) {
const file = {
uri,
name : uri.match(/.{12}.jpg/)[0],
type : "image/png"
};
const options = { keyPrefix: "public/", bucket, region,
accessKey, secretKey, successActionStatus: 201}
RNS3.put(file, options)
.progress(event => {
console.log(`percentage uploaded: ${event.percent}`);
})
.then(res => {
if (res.status === 201) {
console.log('response from successful upload to s3:',
res.body);
console.log('S3 URL', res.body.postResponse.location);
setPic(res.body.postResponse.location);
} else {
console.log('error status code: ', res.status);
}
})
.catch(err => {
console.log('error uploading to s3', err)
})
}
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes : ImagePicker.MediaTypeOptions.All,
allowsEditing : true,
aspect : [4,3],
quality : 1
});
console.log('image picker result', result);
if (!result.cancelled) {
setImage(result.uri);
s3Upload(result.uri);
}
}
In our recent Single Page Application (SPA) style web application, from React, we used "S3 Signed URLs" for efficient upload/download of files and I felt this has resulted in a cleaner design as compared to direct upload/download.
What is the back-end services implemented in?
You can do it on your node server, save it the URL and send it back to the app.
It'll look like:
const AWS = require('aws-sdk');
var s3 = new AWS.S3({accessKeyId:'XXXXXXXXXXXX', secretAccessKey:'YYYYYYYYYYYY', region:'REGION'});
var params = {Bucket: 'yourBucket', Key: 'your_image/your_image.jpg', ContentType: 'image/jpeg'};
s3.getSignedUrl('putObject', params, function (err, url) {
// send it back to the app
});
On the app side you'll have something like:
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
Alert.aler("Upload", "Done");
} else {
Alert.aler("Upload", "Failed");
}
}
}
xhr.open('PUT', presignedUrlReceiveFromServer)
xhr.setRequestHeader('Content-Type', fileType)
xhr.send({ uri: imageFilePath, type: fileType, name: imageFileName })
Hope it helps

How to save and display and image in react-native?

I have a question in react-native. Im using a module called "react-native-image-picker" to pick an image and display it on my app.
Now what i want is to store it somewhere (database, or local storage) and when i open again the app, the image that i choosed should be there. But i dont know what is the best option to do it.
I've already tryied to read some stuff like react-native-fs and fetch-blob but it doesnt help me, i guess.
What is the best option to do it?
Thank you.
First, renders view according to condition. For example if image is available then simply display the image else display TouchableOpacity which will help use to select pictures :
import React, { Component } from React;
import { View, TouchableOpacity, Text, Image } from 'react-native';
import ImagePicker from 'react-native-image-picker';
import AsyncStorage from '#react-native-community/async-storage';
class App extends Component {
constructor(props) {
super(props);
this.state = {
isImageAvailable: false,
profilePic: null
}
}
componentDidMount = () => {
this.getImage();
}
getImage = async () => {
const profilePic = await AsyncStorage.getItem("profilePic");
if (profilePic) {
this.setState({
isImageAvailable: true,
profilePic: JSON.parse(profilePic)
});
}
}
selectProfilePic = () => {
const options = {
title: 'Select Avatar',
storageOptions: {
skipBackup: true,
path: 'images',
},
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
const source = { uri: response.uri };
// You can also display the image using data:
// const source = { uri: 'data:image/jpeg;base64,' + response.data };
AsyncStorage.setItem("profilePic", JSON.stringify(source));
this.setState({
profilePic: source,
isImageAvailable: true
});
}
});
}
render() {
return (
<View>
{
this.state.isImageAvailable && (
<Image source={this.state.profilePic} style={{ width: 200, height: 200 }} />
)
}
{
!this.state.isImageAvailable && (
<TouchableOpacity onPress={this.selectProfilePic}>
<Text>Choose Profile Pic</Text>
</TouchableOpacity>
)
}
</View>
)
}
}
Hope it will help you.
You can use realmdb as an aternative to Asyncstorage.

Is there an alternative to image_picker_saver dependency

I am working on a code to download image in the device but there are androidx incompatibilities with image_picker_saver dependency.So can anyone suggest an alternative for it?
The complete code-
_saveImage(imageNames) async {
await PermissionHandler()
.checkPermissionStatus(PermissionGroup.storage)
.then((status) async {
if (status == PermissionStatus.denied ||
status == PermissionStatus.disabled ||
status == PermissionStatus.unknown) {
await PermissionHandler().requestPermissions(
[PermissionGroup.storage]).then((status1) async {
if (status1.containsValue(PermissionStatus.granted)) {
await get(imageNames).then((res) async {
await ImagePickerSaver.saveFile(fileData: res.bodyBytes)
.then((str) {
File.fromUri(Uri.file(str));
Fluttertoast.showToast(
msg: "Saved to gallery!",
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.BOTTOM,
timeInSecForIos: 1,
backgroundColor: Colors.green,
textColor: Colors.white,
fontSize: 15.0);
});
});
}
});
} else if (status == PermissionStatus.granted) {
await get(imageNames).then((res) async {
await ImagePickerSaver.saveFile(fileData: res.bodyBytes).then((str) {
File.fromUri(Uri.file(str));
Fluttertoast.showToast(
msg: "Saved to gallery!",
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.CENTER,
timeInSecForIos: 1,
backgroundColor: Colors.green,
textColor: Colors.white,
fontSize: 15.0);
});
});
}
});
}
You need a package for decoding/encoding algorithms. I suggest this canonicalized package:
https://pub.dev/packages/image
We will use it.
import 'dart:io' as io;
import 'package:http/http.dart' as http;
import 'package:image/image.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
We need bodyBytes for writing file from network image file:
Future<dynamic> downloadImage() async =>
await http.get(url).then((response) => response.bodyBytes);
Get application working directory:
Future<String> createDir() async =>
await getApplicationDocumentsDirectory().then((dir) => dir.path);
First, we will create [Image] type variable, which is provided by image package then we will convert it to a file both decoding and encoding provided by image package again:
Future<io.File> writeFile(String path, var bodyBytes, String fileName) async {
Image image = decodeImage(bodyBytes);
io.File file = io.File(join(path, fileName));
file.writeAsBytesSync(encodePng(image));
return file;
}
So, you created your files, you need to load them, this is the method you need(You can use restored images by [Image.file] widget):
Future<List<io.File>> loadFiles() async {
List<io.File> images = <io.File>[];
final io.Directory dir = await getApplicationDocumentsDirectory();
print('path: ${dir.path}');
for (io.FileSystemEntity f in dir.listSync()) {
if (f is io.File) {
if (f.path.contains('.jpg')) { //any format you want
images.add(f);
}
}
}
return images;
}

how to upload image in react-admin graphql

i saw example dataprovider in react-admin docs that is handle image upload and convert it to Base64 but i cant use this for graphql dataprovider anyone can help me? actually i want piece of code that handle image upload in react-admin graphql dataprovider
You have to create another client to convert images (or files) to base64 and wrap your graphQL client around it. Like this one:
upload.js
import { CREATE, UPDATE } from 'react-admin'
/**
* Convert a `File` object returned by the upload input into a base 64 string.
* That's not the most optimized way to store images in production, but it's
* enough to illustrate the idea of data provider decoration.
*/
const convertFileToBase64 = file =>
new Promise((resolve, reject) => {
const reader = new FileReader()
reader.readAsDataURL(file.rawFile)
reader.onload = () => resolve(reader.result)
reader.onerror = reject
})
export default dataProvider => (fetchType, resource, params) => {
if (resource === 'Photo' && (fetchType === CREATE || fetchType === UPDATE)) {
const { data, ...rest_params } = params
return convertFileToBase64(data.data).then(base64 => {
return dataProvider(fetchType, resource, {
...rest_params,
data: { ...data, data: base64 }
})
})
}
return dataProvider(fetchType, resource, params)
}
data.js
import buildGraphQLProvider, { buildQuery } from 'ra-data-graphql-simple'
import { createHttpLink } from 'apollo-link-http'
import { ApolloLink } from 'apollo-link'
import { onError } from 'apollo-link-error'
import { AUTH_KEY } from '../authentication'
import { data } from '../schema'
const customBuildQuery = introspection => (fetchType, resource, params) => {
return buildQuery(introspection)(fetchType, resource, params)
}
const httpLink = createHttpLink({ uri: process.env.REACT_APP_GRAPHQL_URI })
const middlewareLink = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
Authorization: `Bearer ${localStorage.getItem(AUTH_KEY)}` || null
}
})
return forward(operation)
})
const errorLink = onError(({ networkError }) => {
if (networkError.statusCode === 401) {
// logout();
}
})
const link = middlewareLink.concat(httpLink, errorLink)
export default () =>
buildGraphQLProvider({
clientOptions: {
link: link
},
introspection: { schema: data.__schema },
buildQuery: customBuildQuery
})
App.js
import React, { Component } from 'react'
import { Admin, Resource } from 'react-admin'
import buildGraphQLProvider from 'data'
import addUploadCapabilities from 'upload'
import dashboard from 'dashboard'
import User from 'resources/User'
import Event from 'resources/Event'
import Photo from 'resources/Photo'
class App extends Component {
state = { dataProvider: null }
componentDidMount () {
buildGraphQLProvider().then(dataProvider => this.setState({ dataProvider }))
}
render () {
const { dataProvider } = this.state
if (!dataProvider) {
return (
<div className='loader-container'>
<div className='loader'>Loading...</div>
</div>
)
}
return (
<Admin
dashboard={dashboard}
title='Admin'
dataProvider={addUploadCapabilities(dataProvider)}
>
<Resource name='User' {...User} />
<Resource name='Event' {...Event} />
<Resource name='Photo' {...Photo} />
</Admin>
)
}
}
export default App

Resources