如何使用Apps脚本从Google驱动器将文件上传到Firebase存储? [英] How to upload files to firebase storage from google drive using Apps Script?

查看:124
本文介绍了如何使用Apps脚本从Google驱动器将文件上传到Firebase存储?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些用户能够将文件上传到Firebase存储,但是他们不精通技术,因此我将让他们首先上传到驱动器,并从存储中镜像驱动器.关键是,如果没有托管服务器,我无法解决问题. Google Apps脚本无法轻松访问Firebase存储(尽管它可以访问两个Firebase数据库),但我需要一台服务器来使用Google Drive API,这可以使用Firebase Cloud函数来完成,但是我想知道是否有更简单的替代方法.

I need some users to be able to upload files to firebase storage, but they're non tech-savvy, so I will let them upload to drive first, and mirror drive from storage. The thing is, I can't figure out how without having to host a server; google apps scripts can't access firebase storage easily (it can access both firebase databases though) and I need a server to use the google drive API, which could be done using firebase cloud functions, but I wonder if there is an easier alternative.

推荐答案

可以使用Apps脚本将图像文件上传到Firebase存储.

An image file can be uploaded to firebase storage using Apps Script.

需要完成4项关键工作:

There are 4 critical things that need to be done:

  • 启用"Google Cloud Storage JSON API"
  • 获取Firebase存储的存储桶"名称
  • 添加" https://www.googleapis.com/auth/devstorage.read_write "作用域到appsscript.json清单文件,以及所有其他已经需要的作用域.
  • 在Firebase存储规则中启用写入"访问权限
  • Enable the "Google Cloud Storage JSON API"
  • Get the "bucket" name of your Firebase Storage
  • Add the "https://www.googleapis.com/auth/devstorage.read_write" scope to the appsscript.json manifest file, along with all other scopes already needed.
  • Enable "Write" access in your Firebase storage rules

您将需要获取OAuth令牌,但不需要OAuth库.

You will need to get an OAuth token, but you don't need an OAuth library.

需要为将要上传文件的Google帐户执行此操作.此处描述的解决方案用于上传文件,其中Apps脚本项目和Firebase存储由同一Google帐户拥有.

This needs to be done for the Google account that will be uploading the file. The solution described here is for uploading a file where the Apps Script project, and the Firebase Storage are owned by the same Google Account.

  • 转到您的Google Cloud Platform-从代码编辑器中选择资源"和"Cloud Platform项目"-单击对话框中的内容以转到您的Cloud Platform.找到"API和服务"部分.点击启用API和服务",搜索"JSON",启用"Google Cloud Storage JSON API"服务.

转到您的Firebase存储设置.查找"gs://your-bucket-name.appsspot.com",这是您的存储桶名称.请勿包含"gs://".存储桶名称的末尾必须包含"appspot.com"部分.

Go to your Firebase Storage settings. Look for "gs://your-bucket-name.appsspot.com" That is your bucket name. Don't include the "gs://" The bucket name needs to have the "appspot.com" part on the end.

在脚本编辑器中,选择文件"和项目属性",然后单击范围"选项卡.复制所有现有的合并范围,然后将其粘贴到某个位置,以便可以将其取回.

From the script editor, choose "File" and "Project Properties" and click the "Scopes" tab. Copy out all the existing scopes, and paste them somewhere so that you can get them back.

从脚本编辑器中,选择查看"和显示清单文件".单击appsscript.json文件将其打开.添加所有现有范围,以及" https://www.googleapis.com/auth/devstorage. read_write "清单文件的作用域.

From the script editor, choose "View" and "Show Manifest file." Click on the appsscript.json file to open it. Add all existing scopes, plus the "https://www.googleapis.com/auth/devstorage.read_write" scope to the manifest file.

{
  "timeZone": "America/New_York",
  "dependencies": {
  },
  "webapp": {
    "access": "ANYONE_ANONYMOUS",
    "executeAs": "USER_DEPLOYING"
  },
  "exceptionLogging": "STACKDRIVER",
  "oauthScopes": [
    "https://mail.google.com/",
    "https://www.googleapis.com/auth/drive",
    "https://www.googleapis.com/auth/script.container.ui",
    "https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/script.scriptapp",
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/userinfo.email",
    "https://www.googleapis.com/auth/devstorage.read_write"
  ]
}

在Firebase存储规则中启用写入"访问权限

allow read, write: if request.auth != null;

您可以通过以下方式获取OAuth令牌:

You can get the OAuth token with:

ScriptApp.getOAuthToken();

因此,您不需要OAuth库,不需要任何SDK,不需要对客户端代码进行任何操作,也不需要来自Firebase服务帐户或旧版的特殊信息数据库秘密.

So, you don't need an OAuth library, you don't need any SDK, you don't need to do anything with client side code, you don't need special information from a firebase service account or the legacy Database Secret.

此代码将图像文件从Google云端硬盘上传到Firebase存储

This code uploads an image file from Google Drive to firebase Storage

注意!任何超过5MB的文件都可能需要一些不同的内容.

function uploadToFirebaseStorage(po) {
try{
  var blob,bucketName,bytes,fileID,fileName,folderName,
    oA_Tkn,options,pathAndName,response,result,url;

  /* See
    https://cloud.google.com/storage/docs/uploading-objects?authuser=0
    for REST API information
  */

  /*
    Firebase uses the Google Cloud Storage API

  */

  bucketName = "your-bucket-name.appspot.com";
  folderName = "folder_name";
  fileName = "file_name";

  pathAndName = folderName + "/" + fileName;

  fileID = po.fileId;

  //curl "https://www.googleapis.com/upload/storage/v1/b/[BUCKET_NAME]/o?uploadType=media&name=[OBJECT_NAME]"
  url = 'https://www.googleapis.com/upload/storage/v1/b/' + bucketName + '/o?uploadType=media&name=' + pathAndName;

  blob = DriveApp.getFileById(fileID).getBlob();
  //Logger.log('blob.getContentType(): ' + blob.getContentType())

  bytes = blob.getBytes();
  //Logger.log('bytes: ' + bytes)

  oA_Tkn = ScriptApp.getOAuthToken();
  options = {
    method: "POST",//curl -X POST
    muteHttpExceptions: true,
    contentLength: bytes.length,
    contentType: blob.getContentType(),//curlv-H "Content-Type: [OBJECT_CONTENT_TYPE]"
    payload: bytes,
    headers: {//curl -H "Authorization: Bearer [OAUTH2_TOKEN]"
    Authorization: 'Bearer ' + oA_Tkn
    }
  }

  response = UrlFetchApp.fetch(url, options);

  result = JSON.parse(response.getContentText());
  Logger.log(JSON.stringify(result, null, 2));


  /*
    A successful return object looks like:

{
"kind": "storage#object",
"id": "bucket-name.appspot.com/online_store/file_name/abc123",
"selfLink": "https://www.googleapis.com/storage/v1/b/bucket-name.appspot.com/o/online_store%2FAAA_Test",
"name": "folder_Name/file_name",
"bucket": "bucket-name.appspot.com",
"generation": "abc123",
"metageneration": "1",
"contentType": "image/jpeg",
"timeCreated": "2018-10-24T00:47:33.435Z",
"updated": "2018-10-24T00:47:33.435Z",
"storageClass": "STANDARD",
"timeStorageClassUpdated": "2018-10-24T00:47:33.435Z",
"size": "950012",
"md5Hash": "abc123==",
"mediaLink": "https://www.googleapis.com/download/storage/v1/b/bucket-name.appspot.com/o/some_name%2FAAA_Test?generation=abc123&alt=media",
"crc32c": "kIY6Qg==",
"etag": "nwrfwfn="
}
*/
}catch(e) {
  Logger.log(e.message + "\n\n" + e.stack)

}
}

function testFB_Upload() {
  uploadToFirebaseStorage({fileId:"Put image file ID here"});
}

首次运行代码时,如果用户尚未启用API,则响应中扩展错误消息中将提供一个链接.因此,您可以修改代码以从错误响应中获取Cloud Console链接.该链接直接指向正确的Cloud Console API,因此用户无需知道如何导航自己的Cloud Console即可找到正确的API.

When the code is run for the first time, if the user has not enabled the API, there is a link provided in the extended error message in the response. So, you could modify the code to get the Cloud Console link from the error response. That link goes directly to the correct Cloud Console API, so the user doesn't need to know how to navigate their Cloud Console in order to find the correct API.

<head>
    <title>Your Site Name</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Firebase App is always required and must be first -->
    <script src="https://www.gstatic.com/firebasejs/5.5.7/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.5.7/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.5.7/firebase-storage.js"></script>

  <script>
    // Initialize Firebase
    //Open the project - click Project Overview - Click the </> icon
    var config = {
      apiKey: "abc123",//Web API key in project settings
      authDomain: "your_name.firebaseapp.com",
      //databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
      projectId: "myID",//In Project Settings
      storageBucket: "myDomain.appspot.com"
    };
    firebase.initializeApp(config);
  </script>

</head>



window.srchForFile = function(po) {//client side code in a script tag
  //This function is called from a success handler AFTER the file has
  //originally been uploaded
try{
  /*
    po - parameters object - {fileID:'123ABC',folderName:'name_here'}
    po.fileID - the ID of the original file that was uploaded
    po.folderName - the name of the firebase folder to search
  */

  /*
    This code assumes that the firebase SDK has been loaded and that the
    firebase class is available
  */

  var fileID,fileName,imagesRef,spaceRef;

  fileID = po.fileId;
  fileName = "IMG_" + fileID;//The file name to search for which must
    //be exactly the same as the file just uploaded - make sure to use
    //a naming convention that is consistent

  if (!STORAGE_REF) {
    STORAGE_REF = firebase.storage().ref();//firebase SDK must be loaded
  }

  imagesRef = STORAGE_REF.child(po.folderName);
  //console.log('imagesRef: ' + imagesRef);

  spaceRef = imagesRef.child(fileName);// Points to the file name
  //console.log('spaceRef: ' + spaceRef);

  spaceRef.getDownloadURL().then(function(url) {
    //console.log('File available at: ' + url);

    if (!url) {
      url = false;
    }

    nextStepAfterFileSrch(url);//Now run another function
  }).catch(function(error) {//There was an error
     // Handle any errors here
     nextStepAfterFileSrch(false);
   }

  );

  //DO NOT HAVE ANY CODE HERE OR IT WILL RUN BEFORE THE ABOVE CODE IS
  //DONE
} catch(e) {
  showErrMsg(e.message);//client side error handling
}
}

这篇关于如何使用Apps脚本从Google驱动器将文件上传到Firebase存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆