1 回答

TA貢獻1802條經驗 獲得超5個贊
問題和解決方法:
當我測試時
gapi.client.drive.files.create
,似乎這種方法雖然可以用元數據創建新文件,但無法包含文件內容。因此,在這個答案中,為了通過包含文件元數據來上傳文件,我想建議使用multipart/form-data
Javascript來上傳文件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。請小心這一點。當您要上傳較大文件時,請勾選斷點續傳。
添加回答
舉報