亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 googledrive api 將文件上傳到 googledrive?

如何使用 googledrive api 將文件上傳到 googledrive?

慕后森 2023-10-20 16:33:24
我按照文檔(https://developers.google.com/drive/api/v3/manage-uploads#http---single-request)中的操作進行操作,但它不起作用:         var fileMetadata = {            name: e.target.files[j].name,            parents: this.currentDirectoryId ? [this.currentDirectoryId] : []          }          var media = {            mimeType: e.target.files[j].type,            body: e.target.files[j]          }          window.gapi.client.drive.files.create({            resource: fileMetadata,            media: media,            fields: 'id, name, mimeType, createdTime'          }).then(res => console.log(res))文件已創建,但為空且名為“Untitled”,mimeType為“application/octet-stream”
查看完整描述

1 回答

?
12345678_0001

TA貢獻1802條經驗 獲得超5個贊

問題和解決方法:

  • 當我測試時gapi.client.drive.files.create,似乎這種方法雖然可以用元數據創建新文件,但無法包含文件內容。因此,在這個答案中,為了通過包含文件元數據來上傳文件,我想建議使用multipart/form-dataJavascript來上傳文件fetch。在這種情況下,訪問令牌由 檢索gapi.auth.getToken().access_token。

  • 不幸的是,從你的腳本中,我無法理解e.target.?因此,在這個示例腳本中,我想提出用于上傳文件的示例腳本,該文件是從輸入標記中檢索到的,并帶有元數據。

示例腳本:

HTML 端:

<input?type="file"?id="files"?name="file">

JavaScript 方面:

const files = document.getElementById("files").files;


const file = files[0];

const fr = new FileReader();

fr.readAsArrayBuffer(file);

fr.onload = (f) => {

? const fileMetadata = {

? ? name: file.name,

? ? parents: this.currentDirectoryId ? [this.currentDirectoryId] : []? // This is from your script.

? }

? const form = new FormData();

? form.append('metadata', new Blob([JSON.stringify(fileMetadata)], {type: 'application/json'}));

? form.append('file', new Blob([new Uint8Array(f.target.result)], {type: file.type}));

? fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', {

? ? method: 'POST',

? ? headers: new Headers({'Authorization': 'Bearer ' + gapi.auth.getToken().access_token}),

? ? body: form

? }).then(res => res.json()).then(res => console.log(res));

};

  • 在此腳本中,從標簽檢索的文件上傳input到 Google Drive,擴展名為multipart/form-data.

筆記:

  • 在此腳本中,它假設您的授權腳本可用于將文件上傳到 Google Drive。請小心這一點。

  • 在此答案中,作為示例腳本,文件上傳為uploadType=multipart.?在本例中,最大文件大小為 5 MB。請小心這一點。當您要上傳較大文件時,請勾選斷點續傳。


查看完整回答
反對 回復 2023-10-20
  • 1 回答
  • 0 關注
  • 311 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號