2017-02-04 199 views
1

我有一個App引擎應用程序。我想使用雲端存儲來存儲一些用戶上傳的文件。Google Appengine雲存儲

我想知道如何進行簡單身份驗證以訪問每個應用程序引擎應用程序隨附的單個免費存儲桶。

我只想讓應用程序本身與Cloud存儲交談,並且用戶不需要與Cloud存儲進行任何交互。每個文件都可以放在同一個文件夾中,只需要App引擎JVM就可以訪問它。

是否有一種簡單的身份驗證方式,無需通過Oauth2等?一個簡單的服務器到服務器的訪問,如果可能的話!

編輯:這是一樣的嗎?

gcloud beta auth application-default login 

編輯2:試過Gcloud上述缺省認證設置。仍然拋出相同的異常。

com.google.cloud.storage.StorageException: Invalid Credentials 

測試代碼,我使用:

private static Storage storage = null; 
static { 
     storage = StorageOptions.getDefaultInstance().getService(); 
    } 

@Override 
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { 
    PrintWriter out = resp.getWriter(); 
    out.println("Hello, world"); 

    testCloudStorage(); 
} 

private void testCloudStorage() throws IOException{ 
    ByteArrayInputStream baIs = new ByteArrayInputStream("TEST FILE CONTENT".getBytes()); 
    uploadFile("test-content.txt", baIs, "xyzabc.appspot.com"); 
} 

/** 
* Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME 
* environment variable, appending a timestamp to end of the uploaded filename. 
*/ 
public String uploadFile(String fileName, InputStream inputStream, final String bucketName) throws IOException { 
    DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS"); 
    DateTime dt = DateTime.now(DateTimeZone.UTC); 
    String dtString = dt.toString(dtf); 
    final String extendedFileName = fileName + dtString; 

    // the inputstream is closed by default, so we don't need to close it here 
    BlobInfo blobInfo = 
     storage.create(
      BlobInfo 
       .newBuilder(bucketName, extendedFileName) 
       // Modify access list to allow all users with link to read file 
       .setAcl(new ArrayList<>(Arrays.asList(Acl.of(Acl.User.ofAllUsers(), Role.READER)))) 
       .build(), 
      inputStream); 
    // return the public download link 
    return blobInfo.getMediaLink(); 
} 

編輯3:這是我遵循的步驟:

  1. 我有一個基本的工作JSP示例應用程序 - 無論devserver並部署版本正常工作
  2. DataStore正在工作 - 插入/更新/刪除
  3. 我添加以下this tutorial
  4. 對於雲存儲的樣本代碼,我跟着this tutorial安裝GCloud SDK和做初始化和設置的缺省auth
+0

向我們展示您基於官方文檔所嘗試的內容。 –

+0

@ZigMandel我已經有一個JSP應用程序在應用程序引擎上運行。我創建了一個測試servlet來測試雲存儲。我只想寫一個字節到測試文件。我現在在問題中添加了servlet代碼。 – Teddy

回答

1

AppEngine上的項目已經與各自的水桶認證。沒有額外的認證需要 - 一旦按照https://cloud.google.com/appengine/docs/java/googlecloudstorageclient/setting-up-cloud-storage創建桶。

然後您可以按照這些文檔或blobstore https://cloud.google.com/appengine/docs/java/blobstore/使用存儲桶。

+0

我經歷了你的第一個鏈接。這可能是問題從本地部署訪問。我從這樣的maven開始項目:mvn appengine:devserver在哪裏可以添加此標誌? --default_gcs_bucket名稱[BUCKET_NAME] – Teddy

+0

謝謝!當我部署到雲時,訪問將自動運行。現在問題只在於開發環境。 – Teddy

+0

我試過這個......但是也沒有工作:mvn appengine:devserver -Ddefault_gcs_bucket_name = abcxyz.appsopt.com – Teddy