简体   繁体   English

React Native,如何展示云存储的图片

[英]React native, how to show an image of cloud storage

I uploaded images but I can't display those images.我上传了图片,但我无法显示这些图片。 I followed the documentation and some examples that I saw, tried but didn't get anything.我按照文档和我看到的一些示例进行了尝试,但没有得到任何东西。 My code now looks like this我的代码现在看起来像这样

const imageRef = storage().ref('images/').child('photo-229634742.jpeg').getDownloadURL();
return(
   ...
   <Text>
      {imageRef}
   </Text>
);

and in this way, it shows this error并以这种方式显示此错误在此处输入图像描述

Can someone help me?有人能帮我吗? I want to show the images I made on the cloud storage我想展示我在云存储上制作的图像

This is my code to upload:这是我要上传的代码:

    const [avatar, setAvatar] = useState(null)
    const [imagePath, setImagePath] = useState()
    const [isLoading, setIsLoading] = useState()
    const [status, setStatus] = useState()

    function chooseFile() {
    setStatus( '' );
    var options = {
        title: 'Select Image',
        storageOptions: {
            skipBackup: true, // do not backup to iCloud
            path: 'images', // store camera images under Pictures/images for android and 
    Documents/images for iOS
        },
    };
    ImagePicker.showImagePicker(options, response => {
        setAvatar(response.uri)
        if (response.didCancel) {
            console.log('User cancelled image picker', storage());
        } else if (response.error) {
            console.log('ImagePicker Error: ', response.error);
        } else if (response.customButton) {
            console.log('User tapped custom button: ', response.customButton);
        } else {
            let path = getPlatformPath(response).value;
            let fileName = getFileName(response.fileName, path);
            setImagePath( path );
            uploadImageToStorage(path, fileName);
            
        }
    });
};

function getFileName(name, path) {
    if (name != null) { return name; }
    
    if (Platform.OS === "ios") {
        path = "~" + path.substring(path.indexOf("/Documents"));
    }
    return path.split("/").pop();
}

function uploadImageToStorage(path, name) {
    setIsLoading({ isLoading: true });
    let reference = storage().ref("images/" + name);
    let task = reference.putFile(path);
    task.then(() => {
        console.log('Image uploaded to the bucket!');
        setIsLoading(false);
        setStatus('Image uploaded successfully');
    }).catch((e) => {
        status = 'Something went wrong';
        console.log('uploading image error => ', e);
        setIsLoading(false);
        setStatus('Something went wrong');
    });
}

/**
 * Get platform specific value from response
 */
function getPlatformPath({ path, uri }) {
    return Platform.select({
        android: { "value": path },
        ios: { "value": uri }
    })
}

function getPlatformURI(imagePath) {
    let imgSource = imagePath;
    if (isNaN(imagePath)) {
        imgSource = { uri: imagePath };
        if (Platform.OS == 'android') {
            imgSource.uri = "images/" + imgSource.uri;
        }
    }
    return imgSource
}

This answer assumes that your images are actually being uploaded to Cloud Storage.此答案假定您的图像实际上正在上传到云存储。

You cannot render an image from within a Text tag , the imageRef constant you're declaring is a method which returns a download url , you want to store that url in state to be able to call it from within an image tag .无法Text tag中渲染图像,您声明的imageRef常量是一种返回download urlmethod ,您希望将 url 存储在state中的 Z9ED39E2EA931586B6A985A69 image tag中调用它。

Code would look something like this:代码看起来像这样:

const [url, setUrl] = useState();

let imageRef = firebase.storage().ref('images/photo-229634742.jpeg');
imageRef
.getDownloadURL()
.then((url) => {
  setUrl(url);
})
.catch((e) => console.log('getting downloadURL of image error => ', e));

and then you can call it from an Image tag as in <Image source={{uri:url}}/>然后你可以像<Image source={{uri:url}}/>一样从 Image 标签中调用它

The reason you need to store the url in state is because the getDownloadUrl() method returns a promise rather than a string of text.您需要将 url 存储在state中的原因是getDownloadUrl()方法返回promise而不是文本字符串 That promise cannot be used directly as a way to render the image. promise 不能直接用作渲染图像的一种方式。 The promise is unaccessible from outside the imageRef function by itself. promise 无法从imageRef function外部访问。 You can check this out by removing the state like this:您可以通过删除 state 来检查这一点,如下所示:

let imageRef = firebase.storage().ref('images/photo-229634742.jpeg');
imageRef
.getDownloadURL()
.catch((e) => console.log('getting downloadURL of image error => ', e));
console.log(url)

You'll see that it returns undefined .您会看到它返回undefined By storing it in state you expand the scope of it and make it accessible from outside the method.通过将其存储在 state 中,您可以扩展它的 scope 并使其可以从方法外部访问。 In that way you can call it from anywhere in the file you're working in.通过这种方式,您可以从您正在处理的文件中的任何位置调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM