Google Drive API – 取得檔案的meta資料
步驟:
結果展示:
- 至Google API Console申請API金錀
- 啟用Google Drive API
- 使用Google Drive API Files: get取得檔案meta資料,底下範例程式,印出檔案的名稱、描述、與建立日期。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://apis.google.com/js/api.js"></script> //載入google api js檔
<script>
var FILE_ID = "18GSM-p3BmsNMdhqr6NUFuYhPBpnHwGX0etM8V_s1X_Q"; //檔案ID
function printFile() {
var request = gapi.client.drive.files.get({
'fileId': FILE_ID
});
// 使用gapi.client.drive.files.get方法,指定'fileId': FILE_ID 來取得檔案的meta資料,方法回傳操作物件,命名為request
request.execute(function (resp) { //執行request.execute方法,並將方法傳回之resp物件為行內函式參數(function(resp)),執行底下敘述
//console.log是進入Chrome開發模式(按F12)後,輸出資料至Console,藉此,我們可觀察程式執行過程中的變數、物件
console.log('Title: ' + resp.title);
console.log('Description: ' + resp.description);
console.log('MIME type: ' + resp.mimeType);
// 下面敘述是典型JS置換HTML文字的用法,用法是使用document.getElementById找到要換資料的標籤ID,再用innerHTML指定內容,請看底下<p id='fileInfo'></p>
document.getElementById('fileInfo').innerHTML = "檔案標題:"+resp.title+"<br>"+
"檔案描述:"+resp.description+"<br>"+
"檔案建立日期:"+resp.createdDate+"<br>";
});
}
function init() {
gapi.client.setApiKey('AIzaSyBQJVpHzi7hEMeQgCmZkkIYVjHkrRj1ClQ'); //設定從Google Developer Console取得的API金錀,記得必須啟用Google Drive API
gapi.client.load('drive', 'v2').then(printFile); //呼叫printFile,印出FILE_ID檔案meta資料
}
gapi.load('client', init);
</script>
</head>
<body>
<p id='fileInfo'></p>
</body>
</html>
- 檔案資源的物件欄位表示:Google Drive Files Resource representations
結果展示:



