как отправить несколько файлов в базовое хранилище и сохранить их URL в базе данных в реальном времени в одной записи - PullRequest
0 голосов
/ 10 апреля 2019

Я хочу отправить несколько файлов в хранилище Fire-base, а между тем нужно сохранить базу данных в режиме реального времени как одну запись, используя java-скрипт. например: file1: urlonfirstfile file2: urlonsecondfile

            for (var i = 0; i < file.length; i++) {

                var task = ref.child(file.name).put(file, metadata);
                task
                    .then(snapshot => snapshot.ref.getDownloadURL())
                    .then((url) => {
                        console.log(url);
                        userDetails.push({

                            email : email,
                            title1: tit,
                            detail1: dit,
                            file:file[i].name

                        });

                    });
            }

1 Ответ

0 голосов
/ 10 апреля 2019

Ваш вопрос довольно неопределенный, какую информацию вы хотите хранить.Поэтому я сделал несколько предположений, чтобы придумать следующий код:

  • Файлы должны быть загружены в область Firebase Storage, специфичную для вошедшего в систему пользователя.(например, "userFiles / CURRENT_USER /...")
  • Информация о загруженных файлах хранится под собственными данными пользователя.(например, "users / CURRENT_USER / uploads /..."
  • " title и detail свойства меняются для каждого файла. Откуда эти свойства берутся, неясно, поэтому я просто собираюсь предположить, что онипередаются через объект metadata.

Приведенного ниже кода должно быть достаточно, чтобы вы начали разбираться со своим собственным решением.

// the array of File objects to upload
const fileObjArray = [ ... ]

// the metadata to store with each file
const metadata = { ... }

// the current user's ID
const currentUserId = firebase.auth().currentUser.uid;

// Where to save information about the uploads
const databaseRef = firebase.database().ref("user").child(currentUserId).child('uploads');

// Create an ID for this set of uploaded files
const uploadId = storageRef.push().key;

// Save files to storage in a subfolder of the user's files corresponding to the uploadId
const storageRef = firebase.storage().ref("userFiles").child(currentUserId).child(uploadId);

// Upload each file in fileObjArray, then fetch their download URLs and then return an object containing information about the uploaded file
var uploadPromiseArray = fileObjArray.map((fileObj) => {
    var uploadTask = storageRef.child(fileObj.name).put(fileObj, metadata)

    return uploadTask.then(uploadSnapshot => {
            // file uploaded successfully. Fetch url for the file and return it along with the UploadTaskSnapshot
            return uploadSnapshot.ref.getDownloadURL().then((url) => {
                    return {
                        downloadUrl: url,
                        snapshot: uploadSnapshot
                    };
                });
        });
});

// uploadPromiseArray is an array of Promises that resolve as objects with the properties "downloadUrl" and "snapshot"
Promise.all(uploadPromiseArray)
    .then((uploadResultArray) => {
        var batchUploadData = {
            timestamp: firebase.database.ServerValue.TIMESTAMP, // use the server's time
            files: [],
            ... // other upload metadata such as reason, expiry, permissions, etc.
        }

        batchUploadData.files = uploadResultArray.map((uploadResult) => {
            // rearrange the file's snapshot data and downloadUrl for storing in the database
            return {
                file: uploadResult.snapshot.name,
                url: uploadResult.url,
                title: uploadResult.snapshot.metadata.customMetadata.title,
                detail: uploadResult.snapshot.metadata.customMetadata.detail
            };
        });

        // commit the data about this upload to the database.
        return databaseRef.child(uploadId).set(batchUploadData);
    })
    .then((dataSnapshot) => {
        // the upload completed and information about the upload was saved to the database successfully

        // TODO: do something
    }, (err) => {
        // some error occured
        // - a file upload failed/was cancelled
        // - the database write failed
        // - permission error from Storage or Realtime Database

        // TODO: handle error
    });

// Warning: this line will be reached before the above code has finished executing

Вот как это выглядиткак в базе данных:

"users": {
    "someUserId-78sda9823": {
        "email": "example@example.com",
        "name": "mr-example",
        "username": "mrexemplary",
        "uploads": {
            "niase89f73oui2kqwnas98azsa": {
                "timestamp": 1554890267823,
                "files": {
                    "1": {
                        "file": "somefile.pdf",
                        "url": "https://firebasestorage.googleapis.com/v0/b/bucket/o/userFiles%2FsomeUserId-78sda9823%2Fsomefile.pdf",
                        "title": "Some File",
                        "detail": "Contains a report about some stuff"
                    },
                    "2": {
                        "file": "screenshot.png",
                        "url": "https://firebasestorage.googleapis.com/v0/b/bucket/o/userFiles%2FsomeUserId-78sda9823%2Fscreenshot.png",
                        "title": "Screenshot of problem",
                        "detail": "Contains an image that shows some stuff"
                    },
                    ...
                }
            },
            ...
        },
        ...
    },
    ...
}

Примечание 1 : Этот код еще не завершен. Отсутствует обработка ошибок для таких вещей, как ошибки прав доступа и неполная загрузка файлов. Это проблема длявам решать.

Примечание 2 : Что касается неполных загрузок файлов, если какой-либо файл не удастся загрузить или получить URL-адрес для загрузки, база данных не будет записана. Один из возможных способов помочьпри этом нужно добавить catch к uploadTask, который возвращает null при ошибке, а затем на шаге uploadResultArray.map(...) пропустить любые uploadResult переменные, которые являются нулевыми, или записать в базу данных, в которой произошел сбой для этого конкретного файла.

Примечание 3 : поскольку Firebase Storage и База данных реального времени используют моментальные снимки, старайтесь, чтобы они назывались uploadSnapshot / fileSnapshot и dataSnapshot соответственно, при использовании обоих в вашем коде, чтобы минимизировать путаницу.Аналогично, назовите ваши ссылки somethingStorageRef / somethingSRef и somethingDatabaseRef / somethingDBRef.

...