Javascript required
Skip to content Skip to sidebar Skip to footer

How to Upload From Device Storage to Google Drive

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

In that location are 4 critical things that need to be done:

  • Enable the "Google Cloud Storage JSON API"
  • Get the "saucepan" name of your Firebase Storage
  • Add the "https://world wide web.googleapis.com/auth/devstorage.read_write" scope to the appsscript.json manifest file, along with all other scopes already needed.
  • Enable "Write" admission in your Firebase storage rules

Yous will need to get an OAuth token, simply y'all don't need an OAuth library.

Enable the "Google Cloud Storage JSON API"

This needs to be done for the Google account that volition exist 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.

  • Go to your Google Cloud Platform - From the lawmaking editor cull, "Resource" and "Deject Platform projection" - Click something in the dialog box to become to your Cloud Platform. Find the "API'due south and Services" section. Click "Enable API's and Services" Search "JSON" Enable the "Google Cloud Storage JSON API" service.

Get the "bucket" name of your Firebase Storage

Become to your Firebase Storage settings. Look for "gs://your-saucepan-name.appsspot.com" That is your saucepan name. Don't include the "gs://" The saucepan proper name needs to have the "appspot.com" role on the terminate.

Add the "https://www.googleapis.com/auth/devstorage.read_write" scope to the appsscript.json manifest file

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

From the script editor, choose "View" and "Prove 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.

Manifest file to look like this, except with your fourth dimension zone and scopes.

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

Enable "Write" access in your Firebase storage rules

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

Firebase Storage Rules

Get the OAuth token:

You can get the OAuth token with:

          ScriptApp.getOAuthToken();                  

So, you don't need an OAuth library, you don't demand whatsoever SDK, you don't demand to practise anything with client side code, you don't need special information from a firebase service business relationship or the legacy Database Secret.

The Lawmaking:

This lawmaking uploads an epitome file from Google Drive to firebase Storage

Note! Any file over 5MB may demand something a lilliputian dissimilar.

          function uploadToFirebaseStorage(po) { endeavor{   var blob,bucketName,bytes,fileID,fileName,folderName,     oA_Tkn,options,pathAndName,response,issue,url;    /* See     https://deject.google.com/storage/docs/uploading-objects?authuser=0     for Residue 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: "Mail service",//coil -X Mail service     muteHttpExceptions: true,     contentLength: bytes.length,     contentType: blob.getContentType(),//curlv-H "Content-Type: [OBJECT_CONTENT_TYPE]"     payload: bytes,     headers: {//curlicue -H "Authorisation: Bearer [OAUTH2_TOKEN]"     Authorization: 'Bearer ' + oA_Tkn     }   }    response = UrlFetchApp.fetch(url, options);    effect = JSON.parse(response.getContentText());   Logger.log(JSON.stringify(event, null, 2));     /*     A successful return object looks like:  { "kind": "storage#object", "id": "bucket-proper name.appspot.com/online_store/file_name/abc123", "selfLink": "https://www.googleapis.com/storage/v1/b/saucepan-proper noun.appspot.com/o/online_store%2FAAA_Test", "name": "folder_Name/file_name", "saucepan": "saucepan-name.appspot.com", "generation": "abc123", "metageneration": "1", "contentType": "prototype/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=" } */ }grab(e) {   Logger.log(e.message + "\north\n" + e.stack)  } }  function testFB_Upload() {   uploadToFirebaseStorage({fileId:"Put image file ID here"}); }                  

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 fault message in the response. So, y'all could modify the lawmaking to get the Deject Console link from the error response. That link goes directly to the correct Cloud Console API, then the user doesn't need to know how to navigate their Deject Console in guild to find the correct API.

How to get the download url afterward the prototype has been uploaded

          <head>     <title>Your Site Name</title>     <meta charset="UTF-8">     <meta proper name="viewport" content="width=device-width, initial-scale=1">      <!-- Firebase App is always required and must be first -->     <script src="https://world wide web.gstatic.com/firebasejs/v.5.7/firebase-app.js"></script>     <script src="https://world wide web.gstatic.com/firebasejs/5.five.7/firebase-auth.js"></script>     <script src="https://www.gstatic.com/firebasejs/5.5.7/firebase-storage.js"></script>    <script>     // Initialize Firebase     //Open up the project - click Project Overview - Click the </> icon     var config = {       apiKey: "abc123",//Spider 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 = office(po) {//client side lawmaking in a script tag   //This function is called from a success handler After the file has   //originally been uploaded attempt{   /*     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 proper noun to search for which must     //be exactly the same as the file just uploaded - make sure to use     //a naming convention that is consequent    if (!STORAGE_REF) {     STORAGE_REF = firebase.storage().ref();//firebase SDK must exist loaded   }    imagesRef = STORAGE_REF.child(po.folderName);   //panel.log('imagesRef: ' + imagesRef);    spaceRef = imagesRef.child(fileName);// Points to the file name   //panel.log('spaceRef: ' + spaceRef);    spaceRef.getDownloadURL().and so(function(url) {     //console.log('File bachelor at: ' + url);      if (!url) {       url = imitation;     }      nextStepAfterFileSrch(url);//At present run another function   }).catch(function(error) {//At that place was an error      // Handle whatever errors here      nextStepAfterFileSrch(false);    }    );    //Practise NOT HAVE ANY CODE Here OR It WILL RUN Earlier THE To a higher place CODE IS   //Washed } catch(east) {   showErrMsg(e.bulletin);//client side error handling } }                  

campbellaudinity.blogspot.com

Source: https://stackoverflow.com/questions/50666355/how-to-upload-files-to-firebase-storage-from-google-drive-using-apps-script