【问题标题】:how to retrieve image from firebase storage and display it on a webpage using google-cloud and node js如何从firebase存储中检索图像并使用google-cloud和node js将其显示在网页上
【发布时间】:2018-10-10 10:55:36
【问题描述】:

我将图像存储在 Firebase 存储中,现在我想将其显示在我的页面上

const firebase = require('./../config/firebase');
const gcloud = require('google-cloud');
const fs = require('fs');

var storage = gcloud.storage({
projectId: 'test-a1e76',
keyFilename: 'test-a1e76-firebase-adminsdk-7111d-124guy123eac.json',
});

var bucket = storage.bucket('test-a1e76.appspot.com');

这就是我的设置的样子。

这是我的get方法。

router.get('/image', function (req,res) {

    var remoteReadStream = bucket.file('download.png').createReadStream();
    var localWriteStream = fs.createWriteStream('/images/watchers/2jIompF9FUZ6A4LnpBcbpHWw8dx2/download.png');
    var ss = remoteReadStream.pipe(localWriteStream);
    res.send(ss);
})

我只试过这个,因为它是写在 npm docs.of google-cloud 作品上的。 我试着把它放在 get 方法中看看它是如何工作的。

然后我得到了这个错误..

Error: ENOENT: no such file or directory, open 'C:\images\test\2jIoasd24zd13ase121s2Ww8dx2\download.png'

这是我的 ajax 获取方法

 $.ajax({
    url:'/user/image',
    type:'GET',
    success:function(data){
      console.log(data.path);

    }
  });

这里有人可以指导我如何从 Firebase 存储中检索图像并将其显示在我的网页上吗?使用这个谷歌云 npm?因为我读到了一些节点 js 不支持 firebase-storage 的线程,所以他们改用 google-cloud。

【问题讨论】:

    标签: javascript node.js firebase firebase-storage


    【解决方案1】:

    我是这样弄的。

    var admin = require("firebase-admin");
    ...
    app.get('/picture', async (req, res) => {
      const fileRef = admin.storage().bucket().file('03aead66e97f0d50ce549b6fffc1b6d7.svg');
      const hash = await fileRef.download()
      res.contentType(fileRef.metadata.contentType);
      res.end(hash[0], 'binary');
    });

    【讨论】:

      【解决方案2】:

      在带有节点的 firebase 函数中,我使用下面的代码运行良好

      How do I upload a base64 encoded image (string) directly to a Google Cloud Storage bucket using Node.js?

      const uuidv4 = require('uuid/v4');
      const uuid = uuidv4();
      
          const os = require('os')
          const path = require('path')
          const cors = require('cors')({ origin: true })
          const Busboy = require('busboy')
          const fs = require('fs')
          var admin = require("firebase-admin");
      
      
          var serviceAccount = {
              "type": "service_account",
              "project_id": "xxxxxx",
              "private_key_id": "xxxxxx",
              "private_key": "-----BEGIN PRIVATE KEY-----\jr5x+4AvctKLonBafg\nElTg3Cj7pAEbUfIO9I44zZ8=\n-----END PRIVATE KEY-----\n",
              "client_email": "xxxx@xxxx.iam.gserviceaccount.com",
              "client_id": "xxxxxxxx",
              "auth_uri": "https://accounts.google.com/o/oauth2/auth",
              "token_uri": "https://oauth2.googleapis.com/token",
              "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
              "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-5rmdm%40xxxxx.iam.gserviceaccount.com"
            }
      
          admin.initializeApp({
              credential: admin.credential.cert(serviceAccount),
              storageBucket: "xxxxx-xxxx" // use your storage bucket name
          });
      
      
          const app = express();
          app.use(bodyParser.urlencoded({ extended: false }));
          app.use(bodyParser.json());
      app.post('/uploadFile', (req, response) => {
          response.set('Access-Control-Allow-Origin', '*');
          const busboy = new Busboy({ headers: req.headers })
          let uploadData = null
          busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
              const filepath = path.join(os.tmpdir(), filename)
              uploadData = { file: filepath, type: mimetype }
              console.log("-------------->>",filepath)
              file.pipe(fs.createWriteStream(filepath))
            })
      
            busboy.on('finish', () => {
              const bucket = admin.storage().bucket();
              bucket.upload(uploadData.file, {
                  uploadType: 'media',
                  metadata: {
                    metadata: { firebaseStorageDownloadTokens: uuid,
                      contentType: uploadData.type,
                    },
                  },
                })
      
                .catch(err => {
                  res.status(500).json({
                    error: err,
                  })
                })
            })
            busboy.end(req.rawBody)
         });
      
      
      
      
      exports.widgets = functions.https.onRequest(app);
      

      【讨论】:

        【解决方案3】:

        您只需要显示图像,对吗?有一种肮脏的方法。

        1- 在您的存储桶上上传一张图片并点击它(在 Firebase 控制台中)。

        2- 在屏幕右侧显示有关您的文件的信息。

        3- 寻找“下载网址”(或类似内容)并点击它。

        4- 这是一个 url 示例:

        https://firebasestorage.googleapis.com/v0/b/coffee-a7e8c.appspot.com/o/coffeeTrue.png?alt=media&token=7f44e575-414d-4d18-8f39-c94a23f6e014

        如您所见,有一个模式: https://firebasestorage.googleapis.com/v0/b/NAME_FILE?alt=media&token=YOUR_TOKEN

        获取您的令牌,现在您可以显示存储桶上的所有图像,仅传递文件名和您的令牌(如此示例)。

        之所以有效,是因为 Firebase 为您的服务提供了一个 Rest API。

        记住:在设置开放规则之前进行身份验证。

        示例:每个人都可以阅读。只有授权用户可以写。

        service firebase.storage {
          match /b/{bucket}/o {
            match /{allPaths=**} {
              allow read: if request.auth == null;
              allow write: if request.auth != null;
            }
          }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-11-29
          • 1970-01-01
          • 2020-05-09
          相关资源
          最近更新 更多