Poot87
Poot87

Reputation: 105

How do I store an uploaded image to my other domain using the MEAN stack?

I've been trying to save simple profile images to my MongoDB database for days now with limited success. It seems to be quite a pain. I can get it to store the image but not retrieve it with a path. I have read that it's a good idea to store your image somewhere else (in my case a registered domain) and only store the url to the image in your database. How do I achieve this using the MEAN stack? Is it even possible?

Otherwise are there any good, potentially free, services that are available?

Example:

router.post('/upload/:profile_id', function (req, res) {

//post to a folder on my external domain

});

Upvotes: 0

Views: 48

Answers (1)

You can store images or any binary files easily with firebase.

You can set your storage up by:

// Set the configuration for your app
  // TODO: Replace with your project's config object
  var config = {
    apiKey: '<your-api-key>',
    authDomain: '<your-auth-domain>',
    databaseURL: '<your-database-url>',
    storageBucket: '<your-storage-bucket>'
  };
  firebase.initializeApp(config);

  // Get a reference to the storage service, which is used to create references in your storage bucket
  var storageRef = firebase.storage().ref();

This is an example on how to upload images:

// File or Blob, assume the file is called rivers.jpg
var file = ...

// Upload the file to the path 'images/rivers.jpg'
// We can use the 'name' property on the File API to get our file name
var uploadTask = storageRef.child('images/' + file.name).put(file);

// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', function(snapshot){
  // Observe state change events such as progress, pause, and resume
  // See below for more detail
}, function(error) {
  // Handle unsuccessful uploads
}, function() {
  // Handle successful uploads on complete
  // For instance, get the download URL: https://firebasestorage.googleapis.com/...
  var downloadURL = uploadTask.snapshot.downloadURL;
});

and finally.. download the image:

// Create a reference to the file we want to download
var imageRef = storageRef.child('images/example.jpg');

// Get the download URL
imageRef.getDownloadURL().then(function(url) {
  // Insert url into an <img> tag to "download"
}).catch(function(error) {
  switch (error.code) {
    case 'storage/object_not_found':
      // File doesn't exist
      break;

    case 'storage/unauthorized':
      // User doesn't have permission to access the object
      break;

    case 'storage/canceled':
      // User canceled the upload
      break;

    ...

    case 'storage/unknown':
      // Unknown error occurred, inspect the server response
      break;
  }
});

Upvotes: 1

Related Questions