gpt4 book ai didi

image - 使用 AWS Amplify 从 React Native 上传到 S3

转载 作者:行者123 更新时间:2023-12-03 23:50:12 25 4
gpt4 key购买 nike

我正在尝试使用 Amplify 从 React Native 将图像上传到 S3。我能够成功上传文本文件。但不是图像。

这是我的代码:

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>
)

}

错误信息是:
error uploading to s3: [Error: Unsupported body payload number]

最佳答案

我最终使用 react-native-aws3 库将图像上传到 S3。
我希望可以更直接地找到有关如何使用 AWS 放大直接上传图像的答案,但它不起作用。所以这就是我所做的:

(此函数的包装器是一个 React 组件。我正在使用“expo-image-picker”中的 ImagePicker、“expo-permissions”中的权限和“expo-constants”中的常量来设置从相机胶卷上传的图像)

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);
}
}

关于image - 使用 AWS Amplify 从 React Native 上传到 S3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59126851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com