我正在尝试在google驱动器中创建文件夹。实际上我正在做的是从我的计算机中取一个文件夹作为输入并将其结构插入谷歌驱动器。此外,我试图插入该文件夹所具有的谷歌驱动器的文件,但此功能现在并不重要。首先,我应该在谷歌驱动器内创建新的文件夹树。我正在使用驱动器api并在获取输入文件夹后我解析它们的路径并将它们放在一个数组中。然后我根据这些数组管理新文件夹的创建。但我坚持的地方是创建嵌套文件夹。例如,我创建了一个'documents'文件夹,然后尝试在'documents'文件夹中创建'files'文件夹。但是在创建'files'文件夹之前,我需要'documents'文件夹的id,所以我可以将它作为父文件分配给'files'文件夹。我应该一个接一个地在for循环中创建文件夹。问题是当我向'documents'文件夹发出请求时,我必须等待request.execute()函数来获取它的id。在我收到“文件”的id请求之前发送但是它不能将id作为参数,因此我无法创建嵌套文件夹。这是一个示例输入文件夹结构,可以清楚地解决问题。 我想在google驱动器中创建此文件夹结构。这是我的代码。
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<script type="text/javascript">
var CLIENT_ID = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var SCOPES = 'https://www.googleapis.com/auth/drive';
var webviewlink = "";
var parentID = [{ id: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" }];
var fileName = "newFolder";
var fileNamesArr = [];
var fileIdArr = [];
var output = document.getElementById('output');
/**
* Called when the client library is loaded to start the auth flow.
*/
function handleClientLoad() {
window.setTimeout(checkAuth, 1);
}
/**
* Check if the current user has authorized the application.
*/
function checkAuth() {
gapi.auth.authorize(
{ 'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': true },
handleAuthResult);
}
/**
* Called when authorization server replies.
*
* @param {Object} authResult Authorization result.
*/
function handleAuthResult(authResult) {
var authButton = document.getElementById('authorizeButton');
var filePicker = document.getElementById('filePicker');
authButton.style.display = 'none';
filePicker.style.display = 'none';
if (authResult && !authResult.error) {
// Access token has been successfully retrieved, requests can be sent to the API.
filePicker.style.display = 'block';
filePicker.onchange = uploadFile;
} else {
// No access token could be retrieved, show the button to start the authorization flow.
authButton.style.display = 'block';
authButton.onclick = function () {
gapi.auth.authorize(
{ 'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': false },
handleAuthResult);
};
}
}
/**
* Start the file upload.
*
* @param {Object} evt Arguments from the file selector.
*/
function uploadFile(evt) {
var files = evt.target.files; // FileList object
var totalFiles = files.length; // length of array
gapi.client.load('drive', 'v2', function () {
for (var k = 0; k < totalFiles; k++) {
var file = evt.target.files[k];
var tmp = file.webkitRelativePath;
var pathNamesArr = tmp.split('/');
console.debug(file);
output.innerText = output.innerText + file.webkitRelativePath + "\n";
for (var i = 0; i < pathNamesArr.length; i++) {
if (!isFile(pathNamesArr[i]) && searchNames(fileNamesArr, pathNamesArr[i])) {
for (var t = 0; t < fileNamesArr.length; t++) {
if (fileNamesArr[t] === pathNamesArr[i]) {
parentID[0].id = fileIdArr[t].id;
}
}
}
if (!isFile(pathNamesArr[i]) && !searchNames(fileNamesArr, pathNamesArr[i])) {
fileNamesArr.push(pathNamesArr[i]);
createNewFile(pathNamesArr[i], parentID, false); //inserts new folders here
}
else if (isFile(pathNamesArr[i])) {
insertFile(file);
}
}
}
});
}
/**
* Insert new file.
*
* @param {File} fileData File object to read data from.
* @param {Function} callback Function to call when the request is complete.
*/
function insertFile(fileData, callback) {
const boundary = '-------314159265358979323846';
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";
var reader = new FileReader();
reader.readAsBinaryString(fileData);
reader.onload = function (e) {
var contentType = fileData.type || 'application/octet-stream';
var metadata = {
'title': fileData.name,
'mimeType': contentType,
'parents': parentID
};
output.innerText = output.innerText + " insert id = " + parentID[0].id + "\n";
var base64Data = btoa(reader.result);
var multipartRequestBody =
delimiter +
'Content-Type: application/json\r\n\r\n' +
JSON.stringify(metadata) +
delimiter +
'Content-Type: ' + contentType + '\r\n' +
'Content-Transfer-Encoding: base64\r\n' +
'\r\n' +
base64Data +
close_delim;
var request = gapi.client.request({
'path': '/upload/drive/v2/files',
'method': 'POST',
'params': { 'uploadType': 'multipart' },
'headers': {
'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
},
'body': multipartRequestBody,
});
/* var request = gapi.client.request({
'path': '/drive/v2/files',
'method': 'POST',
'params': { 'uploadType': 'multipart' },
'body': {
"title": "cat",
"mimeType": "application/vnd.google-apps.folder",
"description": "Some"
}
});*/
if (!callback) {
callback = function (file) {
console.log(file)
};
}
request.execute(callback);
}
}
//Extra Part
function createNewFile(fileName, parentFileId, isPublic) {
output.innerText = output.innerText + " girdi createnewfile2" + fileName + " " + parentFileId[0].id + "\n";
gapi.client.load('drive', 'v2', function () {
output.innerText = output.innerText + " girdi gapi" + "\n";
var request = gapi.client.request({
'path': '/drive/v2/files',
'method': 'POST',
'body': {
"title": fileName,
"mimeType": "application/vnd.google-apps.folder",
"description": "Some",
"parents": parentFileId
}
});
if (isPublic) {
request.execute(function (resp) {
console.log(resp);
parentID = resp.id;
fileIdArr.push({ id : resp.id });
var permissionBody = {
'value': '',
'type': 'anyone',
'role': 'reader'
};
var permissionRequest = gapi.client.drive.permissions.insert({
'fileId': resp.id,
'resource': permissionBody
});
permissionRequest.execute(function (resp) { });
});
}
else {
request.execute(function (resp) {
console.log(resp);
output.innerText = output.innerText + " my new id = " + resp.id + "\n";
parentID = resp.id;
fileIdArr.push({ id : resp.id });
});
}
});
}
//Search the names
function searchNames(namesArr, name) {
if (namesArr.length === 0)
return false;
else {
for (var i = 0; i < namesArr.length; i++) {
if (namesArr[i] === name)
return true;
}
return false;
}
}
//Path is file or directory
function isFile(myName) {
for(var i = 0; i < myName.length; i++){
if (myName.indexOf(".txt") > -1)
return true;
}
return false;
}
</script>
<script type="text/javascript" src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
</head>
<body>
<div>
<input type="file" id="filePicker" multiple directory webkitdirectory mozdirectory />
<input type="button" id="authorizeButton" style="display: none" value="Authorize" />
</div>
<div id="output"></div>