2012-10-02 74 views
3

現在我正在使用此代碼將文件上傳到Google Drive: https://stackoverflow.com/a/11657773/1715263 它適用於文本文件。如何使用javascript在Google Drive上創建文件夾

隨着我試圖創建一個文件夾相同的代碼,使用谷歌從該信息: https://developers.google.com/drive/folder

所以谷歌說,「內容類型:應用程序/ JSON」進入頁眉和「應用/越南盾。谷歌-apps.folder「應該是在體內的MIME類型,這就是我在做什麼在我的代碼,它看起來像現在這樣(?):

function createFolder() 
{ 
    var access_token = googleAuth.getAccessToken(); 

    var json = JSON.stringify({ 
     mimeType: 'application/vnd.google-apps.folder', 
     title: 'Folder', 
    }); 

    var body = "Content-Type: application/json" + "\r\n" + 
       "Content-Length: " + json.length + "\r\n" + "\r\n" + 
       json; 

    gapi.client.request({ 

     'path': '/upload/drive/v2/files/', 
     'method': 'POST', 
     'params': {'uploadType': 'multipart'}, 
     'headers': { 
      'Content-Type': 'application/json', 
      'Authorization': 'Bearer ' + access_token,    
     }, 
     'body': body 
    }).execute(function(file) { 
     document.getElementById("info").innerHTML = "Created folder: " + file; 
    }); 

但它只是創建一個名爲」無題「,它不是文件夾,你無法打開它。

當我將「標題」部分中的「Content-Type」更改爲「application/vnd.google-apps.folder」並刪除「body」部分時,它將創建一個名爲「無標題」的文件夾。

我怎樣才能創建一個具有特定標題的文件夾?

回答

5

終於得到了它的工作通過谷歌搜索Claudios代碼害得我這段代碼:https://stackoverflow.com/a/11361392/1715263

,改變最重要的是「道」,其現在「/ drive/v2/files /」而不是「/ upload/drive/v2/files /」。 我剛剛刪除了'gapi.client.load'函數,添加了標題信息並更改了bodys mimeType。

所以這裏的代碼:

function createFolder() { 

    var access_token = googleAuth.getAccessToken(); 

    var request = gapi.client.request({ 
     'path': '/drive/v2/files/', 
     'method': 'POST', 
     'headers': { 
      'Content-Type': 'application/json', 
      'Authorization': 'Bearer ' + access_token,    
     }, 
     'body':{ 
      "title" : "Folder", 
      "mimeType" : "application/vnd.google-apps.folder", 
     } 
    }); 

    request.execute(function(resp) { 
     console.log(resp); 
     document.getElementById("info").innerHTML = "Created folder: " + resp.title; 
    }); 
} 
+0

檢查文件是否已存在的唯一方法是執行搜索?或者是否也可以自己傳遞一個唯一的ID? – dvtoever

+1

當你創建一個文件夾或上傳一個文件時,你可以通過「resp.id」(在我的代碼示例中)在「request.execute」回調函數中訪問其唯一ID。你可以在某處保存該ID並訪問其相關文件,如http://stackoverflow.com/a/14431112/1715263最後所示,只需添加一些錯誤處理:'if(!resp.error){console.log(「文件已經存在:「+ resp.title);} else {console.log(」File not found:「+ resp.error.message);' – Jex

+0

非常感謝。我想你的答案確實會幫助其他用戶。不過,Google Drive *是我唯一的存儲空間,因此我無法保存該ID。我只知道文件名。所以我想我一直在搜索。 – dvtoever

3

試試下面的代碼:

function createFolder(folderName) { 
    var body = { 
    'title': folderName, 
    'mimeType': "application/vnd.google-apps.folder" 
    }; 

    var request = gapi.client.drive.files.insert({ 
    'resource': body 
    }); 

    request.execute(function(resp) { 
    console.log('Folder ID: ' + resp.id); 
    }); 
} 
+0

嘿!感謝您的快速回復:)當我嘗試你的代碼時,我得到錯誤「未捕獲TypeError:無法讀取未定義的屬性'文件' 然後我GOOGLE了你的代碼,發現這個:http://stackoverflow.com/a/11361392/1715263這幫助我終於得到它的工作:) – Jex

+0

'name',而不是'title',至少對於驅動器v2 –

相關問題