【发布时间】:2020-07-16 17:48:24
【问题描述】:
感谢您阅读我的问题。我正在研究 google drive api,可以将文件从文本 blob 上传到 google drive。但是,我需要手动添加文件夹 ID,以便用户使用它并且不会出现错误,因为他们正在尝试将其上传到 my 文件夹中。如何创建或仅获取文件夹 ID - 甚至可以上传到 GDrive 根目录?任何提示都会有所帮助。
谢谢
// Global vars
const SCOPE = 'https://www.googleapis.com/auth/drive.file';
const gdResponse = document.querySelector('#response');
const login = document.querySelector('#login');
const authStatus = document.querySelector('#auth-status');
const textWrap = document.querySelector('.textWrapper');
const addFolder = document.querySelector('#createFolder');
const uploadBtn = document.querySelector('#uploadFile');
// Save Button and Function
uploadBtn.addEventListener('click', uploadFile);
window.addEventListener('load', () => {
console.log('Loading init when page loads');
// Load the API's client and auth2 modules.
// Call the initClient function after the modules load.
gapi.load('client:auth2', initClient);
});
function initClient() {
const discoveryUrl =
'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest';
// Initialize the gapi.client object, which app uses to make API requests.
// Get API key and client ID from API Console.
// 'scope' field specifies space-delimited list of access scopes.
gapi.client
.init({
apiKey: 'My-API-Key',
clientId:
'My-Client-ID',
discoveryDocs: [discoveryUrl],
scope: SCOPE,
})
.then(function () {
GoogleAuth = gapi.auth2.getAuthInstance();
// Listen for sign-in state changes.
GoogleAuth.isSignedIn.listen(updateSigninStatus);
// Actual upload of the file to GDrive
function uploadFile() {
let accessToken = gapi.auth.getToken().access_token; // Google Drive API Access Token
console.log('Upload Blob - Access Token: ' + accessToken);
let fileContent = document.querySelector('#content').value; // As a sample, upload a text file.
console.log('File Should Contain : ' + fileContent);
let file = new Blob([fileContent], { type: 'application/pdf' });
let metadata = {
name: 'Background Sync ' + date, // Filename
mimeType: 'text/plain', // mimeType at Google Drive
// For Testing Purpose you can change this File ID to a folder in your Google Drive
parents: ['Manually-entered-Folder-ID'], // Folder ID in Google Drive
// I'd like to have this automatically filled with a users folder ID
};
let form = new FormData();
form.append(
'metadata',
new Blob([JSON.stringify(metadata)], { type: 'application/json' })
);
form.append('file', file);
let xhr = new XMLHttpRequest();
xhr.open(
'post',
'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id'
);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.responseType = 'json';
xhr.onload = () => {
console.log(
'Upload Successful to GDrive: File ID Returned - ' + xhr.response.id
); // Retrieve uploaded file ID.
gdResponse.innerHTML =
'Uploaded File. File Response ID : ' + xhr.response.id;
};
xhr.send(form);
}
我没有包括一些不相关的东西。我有这样的东西用于上传文件夹,但不出所料。
function createFolder() {
var fileMetadata = {
name: 'WordQ-Backups',
mimeType: 'application/vnd.google-apps.folder',
};
drive.files.create(
{
resource: fileMetadata,
fields: 'id',
},
function (err, file) {
if (err) {
// Handle error
console.error(err);
} else {
console.log('Folder Id: ', file.id);
}
}
);
}
【问题讨论】:
标签: javascript google-api google-drive-api google-api-js-client