2016-12-19 42 views
7

CO Spojrzałem na:Jak przesłać pliki do GCloud w Node.js?


opinią:

Aktualnie przechowuję obrazy lokalnie i przechowuję ścieżki obrazów w bazie danych czasu rzeczywistego Firebase. Chciałbym przechowywać obrazy w GCloud (aby zmniejszyć koszty).


PYTANIE:

jaki sposób należy zmodyfikować moje aktualny kod przesłać DO GCLOUD?


aktualny kod:

var express = require("express"); 
var router = express.Router(); 
var flash = require("connect-flash"); 

var firebase = require("firebase"); 

var multer = require("multer"); 
var upload = multer({dest:"./public/images/uploads/", limits: {fileSize: 250000}}).single("image"); 


router.get("/", function(req, res, next){ 

    if (firebase.auth().currentUser == null) { 
     global.page_name = "login"; 
     res.render("users/login"); 
    } 
    else { 
     global.page_name = "upload"; 
     res.render("upload"); 
    } 
}); 

router.post("/", function(req, res, next){ 
    upload(req,res, function (err) { 
     if (err) { 
      req.flash("error_msg", "File too large. Max Size: 250KB"); 
      res.redirect("/upload"); 
      return 
     } 


     var title = req.body.title; 
     var section = req.body.section; 

     // Validation 
     req.checkBody('title', 'Title is required').notEmpty(); 
     req.checkBody('title', 'Title is too long, max: 50 charachters !').len(0,50); 
     req.checkBody('section', 'Section is required').notEmpty(); 

     var errors = req.validationErrors(); 

     if(errors){ 
      res.render('upload', { 
       errors: errors 
      }); 
     } 
     else { 

      if (req.file){ 

       console.log("Uploading file..."); 
       var image = req.file.filename; 
       var section = req.body.section.toLowerCase(); 

       var IDref = firebase.database().ref("posts/"+section+"/lastID"); 

       IDref.once("value", function(IDsnapshot){ 
        var number = IDsnapshot.val(); 
        var postRef = firebase.database().ref("posts/"+section).push(); 
        var UID = postRef.key; 
        var post = { 
         title: req.body.title, 
         section: req.body.section, 
         image: image, 
         author: firebase.auth().currentUser.uid, 
         section: section, 
         upvotes: 0, 
         downvotes: 0, 
         id: number + 1, 
         key: UID 
        } 

        IDref.set(post.id); 

        postRef.set(post); 

        var authoredPost = { 
         title: req.body.title, 
         section: section, 
        } 

        var userRef = firebase.database().ref("users/"+firebase.auth().currentUser.uid.toString()+"/posts/"+UID.toString()); 
        userRef.set(authoredPost); 

       }); 

       req.flash("success_msg", "Post Created"); 
       res.redirect("/upload"); 
      } 
      else { 
       console.log("No file uploaded"); 
       req.flash("error_msg", "Image is required"); 
       res.redirect("/upload"); 
      } 
     } 
    }); 
}); 

module.exports = router; 
+0

To naprawdę świetne pytanie. Dziękuję za wpisanie zasobów, które widziałeś. Czy próbowałeś to zrobić? Jeśli masz, jakie problemy masz? https://cloud.google.com/nodejs/getting-started/using-cloud-storage –

Odpowiedz

4

myślę, że lepiej używać firebase.storage w internecie lub aplikacji, aby przesłać bezpośrednio do GCloud ale można użyć tego kodu, aby rozwiązać swój problem

var express = require("express"); 
var router = express.Router(); 
var flash = require("connect-flash"); 

var fs = require('fs'); 
var firebase = require("firebase"); 
var gcloud = require('google-cloud'); 

var multer = require("multer"); 
var upload = multer({dest:"./public/images/uploads/", limits: {fileSize: 250000}}).single("image"); 


// Enable Storage 
var gcs = gcloud.storage({ 
    projectId: 'grape-spaceship-123', 
    keyFilename: '/path/to/keyfile.json' 
}); 

// Reference an existing bucket. 
var bucket = gcs.bucket('my-existing-bucket'); 

router.get("/", function(req, res, next){ 
    if (firebase.auth().currentUser == null) { 
     global.page_name = "login"; 
     res.render("users/login"); 
    } 
    else { 
     global.page_name = "upload"; 
     res.render("upload"); 
    } 
}); 

router.post("/", function(req, res, next){ 
    upload(req,res, function (err) { 
     if (err) { 
      req.flash("error_msg", "File too large. Max Size: 250KB"); 
      res.redirect("/upload"); 
      return 
     } 


     var title = req.body.title; 
     var section = req.body.section; 

     // Validation 
     req.checkBody('title', 'Title is required').notEmpty(); 
     req.checkBody('title', 'Title is too long, max: 50 charachters !').len(0,50); 
     req.checkBody('section', 'Section is required').notEmpty(); 

     var errors = req.validationErrors(); 

     if(errors){ 
      res.render('upload', { 
       errors: errors 
      }); 
     } 
     else { 

      if (req.file){ 


       console.log("image saved successfully in local"); 

       //upload to the GCloud 
       bucket.upload(req.file.filename, function(err, file) { 
        if (!err) { 
         console.log("image saved successfully in GCloud"); 


         //remove local image 
         fs.unlink(req.file.filename, (err) => { 
          if (err) throw err; 
           console.log('successfully deleted /tmp/hello'); 
         }); 


         //store image name in firebase 
         var image = file.name;//may be another key hold the image name. 
         var section = req.body.section.toLowerCase(); 

         var IDref = firebase.database().ref("posts/"+section+"/lastID"); 

         IDref.once("value", function(IDsnapshot){ 
          var number = IDsnapshot.val(); 
          var postRef = firebase.database().ref("posts/"+section).push(); 
          var UID = postRef.key; 
          var post = { 
           title: req.body.title, 
           section: req.body.section, 
           image: image, 
           author: firebase.auth().currentUser.uid, 
           section: section, 
           upvotes: 0, 
           downvotes: 0, 
           id: number + 1, 
           key: UID 
          } 

          IDref.set(post.id); 

          postRef.set(post); 

          var authoredPost = { 
           title: req.body.title, 
           section: section, 
          } 

          var userRef = firebase.database().ref("users/"+firebase.auth().currentUser.uid.toString()+"/posts/"+UID.toString()); 
          userRef.set(authoredPost); 

         }); 

         req.flash("success_msg", "Post Created"); 
         res.redirect("/upload"); 

        } 
       }); 




      } 
      else { 
       console.log("No file uploaded"); 
       req.flash("error_msg", "Image is required"); 
       res.redirect("/upload"); 
      } 
     } 
    }); 
}); 

module.exports = router; 
+0

Nie mogę używać firebase.storage, ponieważ pakiet SDK nie działa z Node.js, a Firebase nie planuje dodawać go do węzła .js :((spróbuję twojego kodu w ciągu najbliższych 24 godzin) – Coder1000

+0

Dla odniesienia: http://stackoverflow.com/questions/39848132/upload-files-to-firebase-storage-using-node-js – Coder1000

+0

czy używasz ten kod i routing przez inny program js-js lub klient, taki jak aplikacja internetowa lub aplikacja na Androida lub iOS? – fingerpich