Upload file to google cloud storage with NodeJS

筅森魡賤 提交于 2020-08-01 17:41:20

问题


My upload.js file contains the following code:

module.exports = {

    up: function () {
        const storage = require('@google-cloud/storage');
        const fs = require('fs');
        const gcs = storage({
            projectId: 'MY_PROJECT_ID',
            keyFilename: './service-account.json'
        });
        var bucket = gcs.bucket('MY_BUCKET');

        bucket.upload('picture.jpg', function(err, file) {
            if (err) throw new Error(err);
        });
    },
}

It works through the terminal but how do I call it on form submission button click or just from different file ?

When I try it gives me:

Cannot read property 'prototype' of undefined

I'm quite new to NodeJs and I don't really know what to do.
Google documentation doesn't help me at all unfortunately :/


回答1:


I would recommend moving your requires to the first line.

const storage = require('@google-cloud/storage');
const fs = require('fs');

module.exports = {
    up: function () {
        const gcs = storage({
            projectId: 'MY_PROJECT_ID',
            keyFilename: './service-account.json'
        });
        const bucket = gcs.bucket('MY_BUCKET');
        bucket.upload('picture.jpg', function(err, file) {
            if (err) throw new Error(err);
        });
    },
}

I would also console.log(storage) and confirm it is defined.




回答2:


`const {
    Storage
} = require('@google-cloud/storage');

const up = () => {
    const gcs = new Storage({
        projectId: 'xxxxxxxxx',
        keyFilename: './service-account.json'
    });
    const bucket = gcs.bucket('xxxxxxxxxx');
    bucket.upload('./test-rev.mkv', function (err, file) {
        if (err) throw new Error(err);
    });
}
`


来源:https://stackoverflow.com/questions/48919153/upload-file-to-google-cloud-storage-with-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!