簡體   English   中英

如何將字符串作為文件上傳到 Google Drive?

[英]How do I upload a string as a file to Google Drive?

這是我的問題:

我想創建一個 Google Sheets 擴展,在其中我基本上從 Google Sheets 中的工作表中提取數據,我使用節點 JS 中的方法對其進行修改。 然后,將我修改的數據放在一個字符串中,我想將該字符串以 csv 或 xml 文件的形式上傳到客戶端的驅動器中。 因此,我沒有可用於上傳文件的本地文件,只有一個字符串變量。 我如何上傳該字符串? 非常感謝,這是我的第一個應用程序,我有點掙扎。

代碼

const {google} = require ('googleapis'); 
const keys = require ('./keys.json'); 
const client = new google.auth.JWT( 
  keys.client_email, null, 
  keys.private_key,
  ['googleapis.com/auth/drive'],
  'https://www.googleapis.com/…' 
); 
client.authorize(function(err, tokens){ 
  if (err){ 
    console.log(err); 
    return 
  } else { 
    console.log('Connected'); 
    gsrun(client); 
  } 
}); 

async function gsrun(cl) { 
  const gsapi = google.sheets({version: 'v4', auth: cl}); 
}

您必須設置文件的元數據和它將包含的數據(重要的是,這種情況下的 MIME 類型必須是text/csv )並且文件的正文將是一個簡單的字符串。 考慮到您已經完成了 OAuth 過程並擁有要插入的字符串,此代碼將幫助您:

module.exports.init =  async function (){
    // Before calling the API, build your own Drive service instance 
    // In the second argument, you must pass your own string message 
    const pro = await uploadSimpleString(drive, null);
    console.log(pro);
  
} 

uploadSimpleString = (drive, message) => {
  // Set file metadata and data
  message = message || 'This is a simple String nice to meet you';
  const fileMetadata = {'name': 'uploadSimpleStringt.csv'};
  const media = {
    mimeType: 'text/csv',
    body: message
  };
  // Return the Promise result after completing its task
  return new Promise((resolve, reject) => {
    try{
      // Call Files: create endpoint
      return drive.files.create({
        resource: fileMetadata,
        media: media,
        fields: 'id'
      },(err, results) => { 
        // Result from the call
        if(err) reject(`Drive error: ${err.message}`);
        resolve(results);
      })
    } catch (error){
      console.log(`There was a problem in the promise: ${error}`);
    }
  });
}

注意

要測試此代碼,請使用以下命令在 CLI 中運行它:

node -e 'require("./index.js").init()'

其中index.js是您的文件名, init()是您的主要功能。

文檔

有關更多信息,請查看這些鏈接並考慮以這種方式使用 [google-drive-api] 標簽,有更多機會獲得幫助,因為更多人將能夠找到您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM