简体   繁体   English

从可调用的 https 云 function 将图像上传到 Firebase 存储

[英]Upload an image into Firebase Storage from a callable https cloud function

I would like to upload an image into Firebase Storage from a callable https cloud function but I don't know how to do that.我想从可调用的 https 云 function 将图像上传到 Firebase 存储,但我不知道该怎么做。

const functions = require('firebase-functions');

const admin = require('firebase-admin');

admin.initializeApp();

const storageBucket = admin.storage().bucket('gs://xxxxx.appspot.com');

exports.test_upload = functions.https.onRequest(async (request, response) => {

    var base64Img = "data:image/jpeg;base64,/9j/4AAQSkZJRg...AoNDQoIC";

    let filename = new Date().getTime() + '.jpg';

    await storageRef.child('/destination/'+filename).putString(base64Img, 'data_url').then(function(snapshot) {

        snapshot.ref.getDownloadURL().then(async (url) => { 
            
            console.log(url);

        });

    });


    response.status(200).send("Done!");

});

Can you help me to understand, how to do that?你能帮我理解,怎么做?

Thank you so much太感谢了

UPDATE: 2020/07/22更新:2020/07/22

const functions = require('firebase-functions');

const admin = require('firebase-admin');

admin.initializeApp();

const storageBucket = admin.storage().bucket('perfume-group.appspot');

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

const storage = new Storage({keyFilename: 'perfume-group-key.json'});

exports.test_upload = functions.https.onRequest(async (request, response) => {

    /// CAS 1: Don't works
    // Source: https://stackoverflow.com/questions/53969468/how-to-store-files-in-firebase-using-node-js

    const fileUrl = 'https://i.pinimg.com/originals/4a/9d/f8/4a9df83774219e0d02bbb9e5dc9be125.jpg';

    const opts = {
        destination: 'destination/file1.jpg',
        metadata: {
            contentType: 'image/jpeg'
        }
    };

    firebase.storage().bucket().upload(fileUrl, opts);

    //////////////////////////////////////////////////

    /// CASE 2: Don't works

    const bucket = storage.bucket('perfume-group.appspot.com');

    bucket.upload(fileUrl, {
        destination: 'destination/file2.jpg',
        metadata: {
            contentType: 'image/jpeg'
        }
    });

    //////////////////////////////////////////////////

    /// CASE 3: Don't works

    const options = {
      destination: 'destination/file3.jpg',
    };

    // Downloads the file
    await storage.bucket('perfume-group.appspot.com').file(fileUrl).download(options);

    //////////////////////////////////////////////////


    response.status(200).send("Done!");

});

is it possible to have examples that work?是否有可能有有效的例子?
Like this page: https://firebase.google.com/docs/storage/web/upload-files喜欢这个页面: https://firebase.google.com/docs/storage/web/upload-files

I understood how to add data to the Database but to add files to the Storage it is not clear.我了解如何将数据添加到数据库,但将文件添加到存储尚不清楚。

Why this explain don't works?为什么这个解释不起作用? ->https://googleapis.dev/nodejs/storage/latest/Bucket.html#upload ->https://googleapis.dev/nodejs/storage/latest/Bucket.html#upload

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');

await bucket.upload('https://i.pinimg.com/originals/4a/9d/f8/4a9df83774219e0d02bbb9e5dc9be125.jpg', function(err, file, apiResponse) {
      
});

After all, my storage still empty.毕竟,我的储藏室还是空的。

You seem to be trying to use the Firebase JavaScript SDK for Cloud Storage inside your Cloud Functions code, which is not possible.您似乎正在尝试在 Cloud Functions 代码中将 Firebase JavaScript SDK 用于 Cloud Storage,这是不可能的。 The Firebase JavaScript SDK for Cloud Storage is only usable in web clients. Cloud Storage 的 Firebase JavaScript SDK 仅在 Z2567A5EC9705EB7AC2DZ98433 客户端中可用。

Within server-side environments, you'll need to use the Firebase Admin SDK to interact with Cloud Storage.在服务器端环境中,您需要使用 Firebase Admin SDK 与 Cloud Storage 交互。 In this case you'll end up using a pre-initialized version of the Node.js SDK for Cloud Storage .在这种情况下,您最终将使用Node.js SDK预初始化版本用于 Cloud Storage。

So to learn how to upload an image in your Cloud Functions, I'd search for Node.js SDK for Cloud Storage upload file .因此,要了解如何在 Cloud Functions 中上传图像,我会搜索Node.js SDK for Cloud Storage upload file This leads to:这将导致:

Took me a while to figure it out so posting it here in case it helps others in the same boat.我花了一段时间才弄明白,所以把它贴在这里,以防它帮助同一条船上的其他人。 I am using formidable serverless to parse the request.我正在使用强大的无服务器来解析请求。

const functions = require("firebase-functions");
const formidable = require("formidable-serverless");
const admin = require("firebase-admin");
admin.initializeApp();

exports.uploadFile = functions.https.onRequest((req, res) => {
  var form = new formidable.IncomingForm();
  form.parse(req, async (err, fields, files) => {
    var file = files.fileToUpload;
    if (err || !file) {
      res.status(500).send(err);
      return;
    }
    var filePath = file.path;
    var filename = file.name;
    var bucket = admin.storage().bucket("nameOfBucket.appspot.com");

    const options = {
      destination: "profile/" + filename,
      contentType: "image/jpeg", //file.path
    };

    //upload image
    await bucket
      .upload(output, options)
      .catch((error) => res.status(500).send(error));
    await res.status(200).send("success");
  });
});

Html form code: Html 形式代码:

<form action="https://yourCloudFunctionsUrl.cloudfunctions.net/uploadFile" method="post" enctype="multipart/form-data">
        <input type="file" accept="image/*" name="fileToUpload" >
        <input type="submit" value="upload">
</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM