Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload image from URL to Firebase Storage

I'm wondering how to upload file onto Firebase's storage via URL instead of input (for example). I'm scrapping images from a website and retrieving their URLS. I want to pass those URLS through a foreach statement and upload them to Firebase's storage. Right now, I have the firebase upload-via-input working with this code:

var auth = firebase.auth();
var storageRef = firebase.storage().ref();

function handleFileSelect(evt) {
  evt.stopPropagation();
  evt.preventDefault();
 var file = evt.target.files[0];


  var metadata = {
    'contentType': file.type
  };

  // Push to child path.
  var uploadTask = storageRef.child('images/' + file.name).put(file, metadata);

  // Listen for errors and completion of the upload.
  // [START oncomplete]
  uploadTask.on('state_changed', null, function(error) {
    // [START onfailure]
    console.error('Upload failed:', error);
    // [END onfailure]
  }, function() {
    console.log('Uploaded',uploadTask.snapshot.totalBytes,'bytes.');
    console.log(uploadTask.snapshot.metadata);
    var url = uploadTask.snapshot.metadata.downloadURLs[0];
    console.log('File available at', url);
    // [START_EXCLUDE]
    document.getElementById('linkbox').innerHTML = '<a href="' +  url + '">Click For File</a>';}

Question what do I replace

var file = evt.target.files[0];

with to make it work with external URL instead of a manual upload process?

var file = "http://i.imgur.com/eECefMJ.jpg"; doesn't work!

like image 326
HalesEnchanted Avatar asked Jun 07 '16 17:06

HalesEnchanted


1 Answers

Javascript solution to this using fetch command.

var remoteimageurl = "https://example.com/images/photo.jpg"
var filename = "images/photo.jpg"

fetch(remoteimageurl).then(res => {
  return res.blob();
}).then(blob => {
    //uploading blob to firebase storage
  firebase.storage().ref().child(filename).put(blob).then(function(snapshot) {
    return snapshot.ref.getDownloadURL()
 }).then(url => {
   console.log("Firebase storage image uploaded : ", url); 
  }) 
}).catch(error => {
  console.error(error);
});
like image 159
dagalti Avatar answered Sep 30 '22 03:09

dagalti