2

所以我想創建一個java.io.File,以便我可以使用它來生成多部分表單POST請求。我有一個com.google.api.services.drive.model.File的形式的文件,所以我想知道,有沒有一種方法可以將此Google文件轉換爲Java文件?這是一個使用Google App Engine SDK的網絡應用程序,該應用程序禁止我試圖使其工作的每種方法將com.google.api.services.drive.model.File轉換爲java.io.File

回答

4

不,您似乎沒有可以從com.google.api.services .drive.model.File到java.io.File。但是仍然可以使用Drive中的數據生成多部分表單POST請求。

因此,com.google.api.services.drive.model.File類用於存儲有關該文件的元數據。它不存儲文件內容。

如果要將文件的內容讀入內存,則Drive文檔中的此代碼段會顯示如何執行此操作。一旦文件在內存中,您可以隨心所欲地做任何事情。

/** 
* Download the content of the given file. 
* 
* @param service Drive service to use for downloading. 
* @param file File metadata object whose content to download. 
* @return String representation of file content. String is returned here 
*   because this app is setup for text/plain files. 
* @throws IOException Thrown if the request fails for whatever reason. 
*/ 
private String downloadFileContent(Drive service, File file) 
    throws IOException { 
    GenericUrl url = new GenericUrl(file.getDownloadUrl()); 
    HttpResponse response = service.getRequestFactory().buildGetRequest(url) 
     .execute(); 
    try { 
    return new Scanner(response.getContent()).useDelimiter("\\A").next(); 
    } catch (java.util.NoSuchElementException e) { 
    return ""; 
    } 
} 

https://developers.google.com/drive/examples/java

This post可能是從谷歌AppEngine上使您的多部分POST請求幫助。

+0

對,上面的代碼基本上是我用來獲取原始字符串文件數據。但我不知道如何用GAE允許的方式重新創建一個java.io.File對象,並且我需要一個java.io.File對象來創建一個FileBody對象,該對象將被附加到多部分形式的職位。檢出您發佈的其他堆棧溢出鏈接 – Dangerbunny

+0

另一個鏈接依賴於存儲在GAE數據庫中的文件。你認爲這是唯一能讓這整件事情起作用的方法嗎? – Dangerbunny

+0

這不完全是一個複製/粘貼解決方案。您有一個存儲在Google驅動器中的文件,並且您希望通過多部分POST請求發送該文件。 GAE文檔顯示瞭如何從Google Drive讀取文件,堆棧溢出示例顯示瞭如何發送多部分POST請求。將這兩樣東西編輯在一起,你就有了解決方案。你可能需要改變一些東西。 –

相關問題