最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Store image in Firebase Storage and save metadata in Firebase Cloud Firestore (Beta) - Stack Overflow

programmeradmin9浏览0评论

I am trying to upload an image to Firebase Storage and save several certain metadata to the Firebase Cloud. I am coding in JavaScript.

Goal is to set also customised metadata to Firebase Cloud for example from a text input field which the user has to fill.

That's how I store images to the Firebase Storage:

storageRef.child('images/' + file.name).put(file, metadata).then(function(snapshot) {
        console.log('Uploaded', snapshot.totalBytes, 'bytes.');
        console.log(snapshot.metadata);
        var url = snapshot.downloadURL;
        console.log('File available at', url);
        // [START_EXCLUDE]
        document.getElementById('linkbox').innerHTML = '<a href="' +  url + '">Click For File</a>';
        // [END_EXCLUDE]
      }).catch(function(error) {
        // [START onfailure]
        console.error('Upload failed:', error);
        // [END onfailure]
      });
      // [END onplete]
    }

I am trying to upload an image to Firebase Storage and save several certain metadata to the Firebase Cloud. I am coding in JavaScript.

Goal is to set also customised metadata to Firebase Cloud for example from a text input field which the user has to fill.

That's how I store images to the Firebase Storage:

storageRef.child('images/' + file.name).put(file, metadata).then(function(snapshot) {
        console.log('Uploaded', snapshot.totalBytes, 'bytes.');
        console.log(snapshot.metadata);
        var url = snapshot.downloadURL;
        console.log('File available at', url);
        // [START_EXCLUDE]
        document.getElementById('linkbox').innerHTML = '<a href="' +  url + '">Click For File</a>';
        // [END_EXCLUDE]
      }).catch(function(error) {
        // [START onfailure]
        console.error('Upload failed:', error);
        // [END onfailure]
      });
      // [END onplete]
    }

I have no idea how to integrate in the upload function another task to write meta data to Firebase Cloud. Any help will be appreciated!

@eykjs @Sam Storie: Thanks for your help. I changed my code. Right now, there is an error which I can't figure it out, whats wrong. Error: TypeError: undefined is not an object (evaluating 'selectedFile.name')

My code:

var selectedFile;

function handleFileSelect(event) {
	//$(".upload-group").show();
	selectedFile = event.target.files[0];
};

function confirmUpload() {
	var metadata = {
		contentType: 'image',
		customMetadata: {
			'dogType': 'Lab',
			'title': $("#imgTitle").val(),
			'caption': $("#imgDesc").val()
		},
	};
	var uploadTask = firebase.storage().ref().child('dogImages/' + selectedFile.name).put(selectedFile, metadata);
		uploadTask.on('state_changed', function(snapshot){
  		
	}, function(error) {
  	
	} );

}

What is wrong with my selectedFile definition? Thanks a lot for help.

Share Improve this question edited Nov 11, 2017 at 8:20 peachmeier asked Nov 1, 2017 at 12:51 peachmeierpeachmeier 1332 gold badges2 silver badges7 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 8

Maybe you could upload the data to Firestore after you finished the upload.

storageRef.child('images/' + file.name).put(file, metadata).then(function(snapshot) {
console.log('Uploaded', snapshot.totalBytes, 'bytes.');

let db = firebase.firestore();
let dbRef = db.collection("images").doc(file.name);

let setData = dbRef.set({
    //yourdata here
    downloadURl: snapshot.downloadURL
}).then( () => {
    console.log("Data stored in Firestore!");
});

// your actions

If I understand what you're after this should easily be done with Firebase functions:

https://firebase.google./docs/storage/extend-with-functions

You can trigger a function when something in storage changes, and thus easily write data to either the realtime database, or the new(er) Firestore database.

Here's a simple snippet from the page I referenced to see what this might look like:

exports.generateThumbnail = functions.storage.object().onChange(event => {
  // ...
});

Source Link

Image Upload in Firestore and saving meta info on Cloud Storage

import { AngularFireStorage, AngularFireUploadTask } from '@angular/fire/storage';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { finalize, tap } from 'rxjs/operators';

...
...
...

// The main task
this.task = this.storage.upload(path, file, { customMetadata });

// Get file progress percentage
this.percentage = this.task.percentageChanges();
this.snapshot = this.task.snapshotChanges().pipe(

  finalize(() => {
    // Get uploaded file storage path
    this.UploadedFileURL = fileRef.getDownloadURL();

    this.UploadedFileURL.subscribe(resp=>{
      this.addImagetoDB({
        name: file.name,
        filepath: resp,
        size: this.fileSize
      });
      this.isUploading = false;
      this.isUploaded = true;
    },error=>{
      console.error(error);
    })
  }),
  tap(snap => {
      this.fileSize = snap.totalBytes;
  })
)

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论