简体   繁体   English

Firebase storage-resize-images 未由存储桶上传触发

[英]Firebase storage-resize-images not triggered by bucket upload

I'm using a Firebase function to upload images to Storage.我正在使用 Firebase function 将图像上传到存储。

I installed the extension firebase/storage-resize-images@0.1.29我安装了扩展firebase/storage-resize-images@0.1.29

When I upload an image directly within the dashboard, the resize happens.当我直接在仪表板中上传图像时,会发生调整大小。

However, images uploaded with my functions do not trigger the resize.但是,使用我的函数上传的图像不会触发调整大小。

What am I missing here?我在这里想念什么?

async function migrateImageFromURL (folder, url, name, callback) {
  const {filePath, fileName} = await downloadRemoteUrlImage(url, name.split('.')[0])

  const bucket = admin.storage().bucket();
  const destination = `dev/${folder}/${fileName}`;

  try {
      await bucket.upload(filePath, {
          destination: destination,
          gzip: true,
          metadata: {
            fileName,
            contentType: `image/${fileName.split('.')[1]}`,
            cacheControl: 'public, max-age=31536000',
          },
      });
      callback(destination)
  }
  catch (e) {
      throw new Error("uploadLocalFileToStorage failed: " + e);
  }

 return ''
};

Create a cloud function with busyboy用busyboy创建云busyboy

  • Create a sample firebase function创建示例 firebase function

  • Copy the code for package.json复制package.json的代码

  • Run the command to install the node modules运行命令安装节点模块

    npm run
  • Copy the code for index.js复制index.js的代码

  • To generate a private key file for your service account:要为您的服务帐户生成私钥文件:

    • In the Firebase console, open Settings > Service Accounts .在 Firebase 控制台中,打开 Settings > Service Accounts

    • Click Generate New Private Key, then confirm by clicking Generate Key.单击 Generate New Private Key,然后单击 Generate Key 进行确认。

    • Choose Node Js选择Node Js

    • Securely store the JSON file containing the key.安全地存储包含密钥的 JSON 文件。

  • Copy the firebase-admin-sdk.json file inside the function directory复制 function 目录下的 firebase firebase-admin-sdk.json文件

  • Deploy the function to firebase将 function 部署到 firebase

     firebase deploy --only functions
  • Get the http endpoint from the firebase console从 firebase 控制台获取http endpoint

Index.js索引.js

const functions = require("firebase-functions");
const os = require("os");
const path = require("path");
const spawn = require("child-process-promise").spawn;

//To enable Cross AXIS 
//Change to False to avoid DDOS
const cors = require("cors")({ origin: true });

//Parse Files
const Busboy = require("busboy");

//Files System
const fs = require("fs");

var gcconfig = {
    // Get the project ID from firebaserc
  projectId: "<project_id>",
//   Write the name of the file in the root director which contains the private key of firebase-admin-sdk
  keyFilename: "firebase-admin-sdk.json"
};

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

exports.uploadFile = functions.https.onRequest((req, res) => {

  //Allowing CROSS SITE
  cors(req, res, () => {
    if (req.method !== "POST") {
      return res.status(500).json({
        message: "Not allowed"
      });
    }

    console.log("Starting BusBOY");
    const busboy = Busboy({ headers: req.headers});
    let uploadData = null;
    
    //File parsing
    busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {

        // Firebase cloudfunction will have some tmpdirectory tmpdir
        // It will be cleaned up after execution
      console.log("File function reached ");

      console.log("Temp folder is "+os.tmpdir());
      console.log("File name is "+filename.filename);

      const filepath = path.join(os.tmpdir(),filename.filename);

      console.log("Location of file is "+filepath);
      uploadData = { file: filepath, type: mimetype };

      console.log("Writing to temp file storage");
      //Writing file to storage
      file.pipe(fs.createWriteStream(filepath));

      //Extra Details such as limit error
      file.on('limit', () => {
        console.log("Reached size limit");
        debugLog(options, `Size limit reached for ${field}->${filename.filename}, bytes:${getFilesizeInBytes(filename)}`);
      });
        file.on('end', () => {
        const size = getFilesizeInBytes(filename.filename);
        console.log("File size is "+size+" bytes");
       });
       file.on('error', (err) => {
        console.log("File format error");
       });

    });

    //For Form data Listener
    // busboy.on("field",()=>{

    // });

    // Finishes the whole process, only upload after that
    busboy.on("finish", () => {

        // Firebase storage, Inside the console itself
        // Copy the folder location
        // gs://<Project_id>.appspot.com
        // Remove the gs String

      console.log("Finished BusBoy");
      var your_project_id="<your_project_id>.appspot.com";

      const bucket = gcs.bucket(your_project_id);
      console.log("Uploading Image to firebase");
      
      bucket
        .upload(uploadData.file, {
          uploadType: "media",
          metadata: {
            metadata: {
              contentType: uploadData.type
            }
          }
        })
        .then(() => {
            // Success
          console.log("Uploaded Successfully");
          res.status(200).json({
            message: "It worked!"
          });
        })
        .catch(err => {
            // Error
            console.log("Error while uploading");

          res.status(500).json({
            error: err
          });
        });
    });

    //End the parsing
    console.log("End Parsing");
    busboy.end(req.rawBody);

  });
});

//Finding the file size from the filename
function getFilesizeInBytes(filename) {
  var stats = fs.statSync(filename);
  var fileSizeInBytes = stats.size;
  return fileSizeInBytes;
}

package.json package.json

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase emulators:start --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions:uploadFile",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "14"
  },
  "main": "index.js",
  "dependencies": {
    "firebase-admin": "^9.8.0",
    "firebase-functions": "^3.14.1",
    "@google-cloud/storage": "^6.0.1",
    "busboy": "^1.6.0",
    "child-process-promise": "^2.2.1",
    "cors": "^2.8.5"
  },
  "devDependencies": {
    "firebase-functions-test": "^0.2.0"
  },
  "private": true
}

For more details更多细节

Checkout https://github.com/katmakhan/firebase-course/tree/master/Firebase%20Cloud%20Function/Image%20Uploader结帐https://github.com/katmakhan/firebase-course/tree/master/Firebase%20Cloud%20Function/Image%20Uploader

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

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