Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store image in Firebase Storage and save metadata in Firebase Cloud Firestore (Beta)

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 oncomplete]
    }

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.

like image 482
peachmeier Avatar asked Nov 01 '17 12:11

peachmeier


2 Answers

Source Link

Image Upload in Firestore and saving meta info on Cloud Storage

enter image description here

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;
  })
)
like image 89
Code Spy Avatar answered Oct 30 '22 13:10

Code Spy


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
like image 29
Eyk Rehbein Avatar answered Oct 30 '22 12:10

Eyk Rehbein