如何在 Node.js 中将文件上传到 GCloud?

Posted

技术标签:

【中文标题】如何在 Node.js 中将文件上传到 GCloud?【英文标题】:How to upload files to the GCloud in Node.js? 【发布时间】:2017-05-05 00:46:51 【问题描述】:

我看到了什么:

Integrate with Google Cloud Platform

Upload files to Firebase Storage using Node.js


想法:

我目前将图像存储在本地,并将图像路径存储在 Firebase 实时数据库中。我想将图像存储在 GCloud 中(以降低成本)。


问题:

我应该如何修改我当前的代码以上传到 GCLOUD ?


当前代码:

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;

【问题讨论】:

这是一个非常好的问题。感谢您列出您所看到的资源。你试过关注这个吗?如果你有,你有什么问题? cloud.google.com/nodejs/getting-started/using-cloud-storage 【参考方案1】:

我认为最好在 web 或应用程序中使用 firebase.storage 直接上传到 GCloud,但您可以使用此代码来解决您的问题

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;

【讨论】:

我无法使用 firebase.storage,因为 SDK 不能与 Node.js 一起使用,而且 Firebase 没有计划为 Node.js 添加它 :((我将在接下来的 24 小时内尝试您的代码) 供参考:***.com/questions/39848132/… 您是否使用此代码并通过其他节点 js 程序或客户端(如 web 应用程序或 android 应用程序或 ios 应用程序)进行路由? 当然你有一个客户端,因为当你通过另一个节点js程序调用它时不需要上传,并且在客户端中你可以使用firebase.storage

以上是关于如何在 Node.js 中将文件上传到 GCloud?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 node.js、Express 和 knox 将文件从浏览器上传到 Amazon S3? [关闭]

如何在 Node.js / Express.js 中将中间件放在它自己的文件中

如何使用 javascript/node js 从数据库中将图片动态加载到网页上

如何使用 ios 应用程序将图像上传到 Node.JS 服务器

Node.js:啥是 ENOSPC 错误以及如何解决?

Node.js:如何在不上传文件列表的情况下检查文件夹是不是为空