React Native:将本地图像转换为 url

React Native : convert local image to url

我是 React Native(本例中为 Expo)和 Firebase 数据库的新手。

我的问题是,当我使用 Image Picker 在我的应用程序中上传图片时,link 是本地 link,因此只能用我的设备读取,然后在我擦除时删除缓存

这是我的代码:

useEffect(() => {
    (async () => {
        if (Platform.OS !== "web") {
            const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
            if (status !== "granted") {
                alert("Sorry, we need camera roll permissions to make this work!");
            }
        }
    })();
}, []);

const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.All,
        allowsEditing: true,
        quality: 1,
    });
    
    if (!result.cancelled) {
        setImage(result.uri);
    }
};

// My current image is locate to : "file:///data/user/0/host.exp.exponent/cache/
// ExperienceData/ImagePicker/2abe4097-05ed-4d23-5648-f279d5a6f995.jpg"

// And what I want is to locate my image to : "https://someting..."

所以我想将此图像 uri link 转换为 url link,以便共享且永不删除。

有人知道如何进行吗?

非常感谢!

让我们将问题分解如下:

1.从媒体库中选择一张图片。

const pickImage = async () => {
   let result = await ImagePicker.launchImageLibraryAsync({
       mediaTypes: ImagePicker.MediaTypeOptions.All,
       allowsEditing: true,
       quality: 1,
   });
   
   if (!result.cancelled) {
       setImage(result.uri);
   }
};


2。获取图像 BLOB 数据


  const blob = await new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function () {
      resolve(xhr.response);
    };
    xhr.onerror = function (e) {
      reject(new TypeError("Network request failed"));
    };
    xhr.responseType = "blob";
    xhr.open("GET", [IMAGE_URI_HERE], true);
    xhr.send(null);
  });

3。将图像 BLOB 上传到远程服务器(Firebase 存储)


  const metadata = { contentType: "image/jpg" };

  const imgRef = firebase.storage().ref('folderName/fileName');

  await imgRef.put(blob, metadata);

  // We're done with the blob, close and release it
  blob.close();
 
  // Image permanent URL 
  const imgURL = await imgRef.getDownloadURL();