将我上传的图片从 1 张照片扩展到 5 张照片; map/foreach?

Expand my image upload from 1 to 5 photos; map/foreach?

我正在创建一个应用程序,您可以在其中将照片和一些其他数据上传到 Firebase。上传部分与一张图片完美配合。但是我现在添加了一张多图图片(select 1 到 5 张图片),并希望我的图片上传功能上传 5 张图片而不是 1 张。 图片上传需要提供 1 张图片,那么我如何才能 rear运行ge 我的代码来上传数组中 x 数量的照片?

图片被添加到照片数组中,数据如下(下面显示的输出是 console.log 来自获取的图像);

Array [
  Object {
    "exists": true,
    "file": "ph://8905951D-1D94-483A-8864-BBFDC4FAD202/L0/001",
    "isDirectory": false,
    "md5": "f9ebcab5aa0706847235887c1a7e4740",
    "modificationTime": 1574493667.505371,
    "size": 104533,
    "uri": "ph://8905951D-1D94-483A-8864-BBFDC4FAD202/L0/001",
  },

使用这个 didFocus,我检查是否设置了 fethedImages 参数并将照片数组设置为获取的图像(所以上面显示的所有数据)

 const didFocusSubscription = props.navigation.addListener(
        'didFocus', () => {
            let fetchedImages = props.navigation.getParam('fetchedImages')
            console.log(fetchedImages)
            setPhotos(fetchedImages)
            setImageValid(true)
            calculateImageDimensions()
        }
    );

当我保存页面并开始发送数据时,我 运行 以下命令 uploadImage 函数是 运行 和 returns 上传 url,然后是稍后在分发函数中保存到 Firebase 数据库,以便稍后获取;

 uploadurl = await uploadImageAsync(photos)

所以 uploadImageAsync 从转发的照片数组开始。如何确保为数组中的每个 photo.uri 启动下面的函数?我可以为此使用 .map of for each 吗?我应该在什么情况下使用它? 此外,我不太确定如何发回要与其余信息一起保存的一组 URL。

  async function uploadImageAsync(photos) {
        console.log('uploadImage is gestart')
        // Why are we using XMLHttpRequest? See:
        // https://github.com/expo/expo/issues/2402#issuecomment-443726662
        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', photos, true);
            xhr.send(null);
        });

        const ref = firebase
            .storage()
            .ref()
            .child(uuid.v4());
        const snapshot = await ref.put(blob);

        // We're done with the blob, close and release it
        blob.close();

        return await snapshot.ref.getDownloadURL();

    }

==============由于上传进度已编辑====================

我又一次走得更远了。但是图片上传功能现在是运行ning,因为是多张图片我想等待所有图片的响应再继续。

    try {
        uploadurl = await uploadImageAsync()
        address = await getAddress(selectedLocation)
        console.log(uploadurl)
        if (!uploadurl.lenght) {
            Alert.alert('Upload error', 'Something went wrong uploading the photo, plase try again', [
                { text: 'Okay' }
            ]);
            return;
        }

        dispatch(

在我启动uploadImageAsync函数的这一刻。在 console.log 的帮助下,我看到它正在上传图片,它们也显示在网上。但是当图片正在上传时上传 url 已经 returns 和 0 并显示警报和停止功能。

uploadImageAsync = async () => {
    const provider = firebase.database().ref(`providers/${uid}`);
    let imagesArray = [];
    try {
        await photos.map(img => {
            let file = img.data;
            const path = "Img_" + uuid.v4();
            const ref = firebase
                .storage()
                .ref(`/${uid}/${path}`);
            ref.putString(file).then(() => {
                ref
                    .getDownloadURL()
                    .then(images => {
                        imagesArray.push({
                            uri: images
                        });
                        console.log("Out-imgArray", imagesArray);
                    })
        return imagesArray   <== this return imagesArray is fired to early and starts the rest of my upload function. 
    } catch (e) {
        console.error(e);
    }
};

因此,Discord 聊天为我指出了 promise.all 函数的方法,以使其发挥作用。我试过了,但打开了另一个堆栈溢出主题来让它工作。

我的图片上传功能的解决方案在上面的题目中;

uploadImages = () => {
    const provider = firebase.database().ref(`providers/${uid}`);
    // CHANGED: removed 'let imagesArray = [];', no longer needed

    return Promise.all(photos) // CHANGED: return the promise chain
        .then(photoarray => {
            console.log('all responses are resolved successfully');
            // take each photo, upload it and then return it's download URL
            return Promise.all(photoarray.map((photo) => { // CHANGED: used Promise.all(someArray.map(...)) idiom
              let file = photo.data;
              const path = "Img_" + uuid.v4();
              const storageRef = firebase // CHANGED: renamed 'ref' to 'storageRef'
                    .storage()
                    .ref(`/${uid}/${path}`);
              let metadata = {
                  contentType: 'image/jpeg',
              };

              // upload current photo and get it's download URL
              return storageRef.putString(file, 'base64', metadata) // CHANGED: return the promise chain
                .then(() => {
                  console.log(`${path} was uploaded successfully.`);
                  return storageRef.getDownloadURL() // CHANGED: return the promise chain
                    .then(fileUrl => ({uri: fileUrl}));
                });
            }));
        })
        .then((imagesArray) => {                       // These lines can
          console.log("Out-imgArray: ", imagesArray)   // safely be removed.
          return imagesArray;                          // They are just
        })                                             // for logging.
        .catch((err) => {
          console.error(err);
        });
};