react-native - React Native - 将图像从本地缓存发送到 firebase 存储

标签 react-native firebase-storage

在 Android 上使用 React Native,我试图将用户的图像配置文件从本地缓存发送到 firebase 存储桶。如果我将其作为 blob 发送或 Uint8Array ,当我在 firebase 上打开图像时,出现错误 The image "https://firebasestorage<resto of url here>" cannot be displayed because it contain errors .如果我将其作为 base64 data url 发送,它没有上传到存储桶,我收到消息 Firebase Storage: String does not match format 'base64': Invalid character found .我已经用解码器测试了 base64 数据 url,它可以工作。我怎样才能让它工作,无论是作为 blob、Uint8Array 还是 base64?。这是代码:

作为 blob

let mime = 'image/jpeg';
getFile(imageUri)
  .then(data => {
    return new Blob([data], { type: mime });
  })
  .then(blob => {
    return imageRef.put(blob, { contentType: mime });
  })

async function getFile(imageUri) {
  let bytes = await FileSystem.readAsStringAsync(imageUri);
  return Promise.resolve(bytes);
}

作为 Uin8Array

let mime = 'image/jpeg';
getFile(imageUri)
  .then(data => {
    return imageRef.put(data, { contentType: mime });
  })


async function getFile(imageUri) {
  let bytes = await FileSystem.readAsStringAsync(imageUri);
  const imageBytes = new Uint8Array(bytes.length);
  for ( let i = 0; i < imageBytes.length; i++) {
    imageBytes[i] = bytes.charCodeAt(i);
  }
  return Promise.resolve(imageBytes);
}

作为 base64 数据 url

imageBase64Url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAADCAIAAADZSiLoAAAAF0lEQVQI12P8//8/AwMDAwMDEwMMIFgAVCQDA25yGkkAAAAASUVORK5CYII=";
return imageRef.putString(imageBase64Url, 'data_url');

URI

我从这个对象中检索 uri:

Object {
    "cancelled": false,
    "height": 60,
    "type": "image",
    "uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252FMCC_Project-ee81e7bd-82b1-4624-8c6f-8c882fb131c4/ImagePicker/6ec14b33-d2ec-4f80-8edc-2ee501bf6e92.jpg",
    "width": 80,
 }

最佳答案

我们发现我尝试检索图片并将其发送到 Firebase 存储桶的方式至少有两个问题:

1) 当从内存中检索图像并尝试将其作为 blob 发送到存储桶时,FileSystem.readAsStringAsync(imageUri) 由于某种原因返回损坏的文件

2) 相反,当尝试将图像作为 base64 保存到 Firebase 存储桶时,问题似乎出在 Firebase 上,因为这里甚至没有提供完全相同的示例 https://firebase.google.com/docs/storage/web/upload-files正在工作。

解决方法:

我们使用 XMLHttpRequest 而不是 Expo 的 FileSystem 从本地缓存中检索图像,并将其作为 blob 保存到 Firebase 存储桶中:

import React, { Component } from 'react';
import firebase from './firebase';

export default async function saveImage(picture, uid) {
  const storageRef = firebase
    .storage('gs://*<bucket-here>*')
    .ref(uid + '/' + 'profile-picture.jpeg');

  const blob = await new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function() {
      resolve(xhr.response);
    };
    xhr.onerror = function(e) {
      console.log(e);
      reject(new TypeError('Network request failed'));
    };
    xhr.responseType = 'blob';
    xhr.open('GET', picture.uri, true);
    xhr.send(null);
  });

  const metadata = {
    contentType: 'image/jpeg',
  };

  return (downloadURL = await new Promise((resolve, reject) => {
    try {
      storageRef.put(blob, metadata).then(snapshot => {
        snapshot.ref.getDownloadURL().then(downloadURL => {
          resolve(downloadURL);
        });
      });
    } catch (err) {
      reject(err);
    }
  }));
}

关于react-native - React Native - 将图像从本地缓存发送到 firebase 存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53570265/

相关文章:

css - react native : Modal overlaps a root component

firebase - 使用 React Native 将图像源设置为 Firebase Storage URL

ios - 将图像上传到 Firebase 存储

android - Firebase 上传/下载 pdf 文件

react-native - 如何在react native中输入确认码

javascript - Require() 在 native react 中

javascript - 如何在 React Native ios 中从 api 添加列表到下拉列表?

javascript - 分隔列表内的元素

android - Kotlin - Firebase 和 Glide - 获取图像 url,以便 glide 可以使用它

Node.js错误: Cannot find module 'firebase/storage'