2014-11-06 9 views
3

현재 Google Cloud Storage에 파일을 업로드 할 수있는 프로젝트를 진행 중입니다. 그래서 우리는 버킷을 생성하고 난 내 로컬 "정상"응용 프로그램에 메이븐 의존성을 추가 : Google Cloud Storage에 이미지 저장

<dependencies> 
    <dependency> 
     <groupId>com.google.appengine.tools</groupId> 
     <artifactId>appengine-gcs-client</artifactId> 
     <version>RELEASE</version> 
    </dependency> 
</dependencies> 

가 그럼 난 로컬 파일을 읽기 시작하고, 단지 주에 구글 클라우드 스토리지에 저를 밀어 시도 :

try { 
    final GcsService gcsService = GcsServiceFactory 
     .createGcsService(); 

    File file = new File("/tmp/test.jpg"); 
    FileInputStream fis = new FileInputStream(file); 
    GcsFilename fileName = new GcsFilename("test1213","test.jpg"); 
    GcsOutputChannel outputChannel; 
    outputChannel = gcsService.createOrReplace(fileName, GcsFileOptions.getDefaultInstance()); 
    copy(fis, Channels.newOutputStream(outputChannel)); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

copy 방법은 다음과 같습니다

:

private static final int BUFFER_SIZE = 2 * 1024 * 1024; 

private static void copy(InputStream input, OutputStream output) 
     throws IOException { 
    try { 
     byte[] buffer = new byte[BUFFER_SIZE]; 
     int bytesRead = input.read(buffer); 
     while (bytesRead != -1) { 
      output.write(buffer, 0, bytesRead); 
      bytesRead = input.read(buffer); 
     } 
    } finally { 
     input.close(); 
     output.close(); 
    } 
} 

나는 그에게서 얻는 모든이입니다 The API package 'channel' or call 'CreateChannel()' was not found

그것은 이러한 AppEngine에 앱없이 appengine.tools -> gcs-client를 사용 할 수있는 방법이 없다는 것을 말한다 :

The API package 'file' or call 'Create()' was not found. 
도 빙에서 검색, 구글에서 많이 검색 문서화를 읽은 후 나는이 항목을 발견했다. 그러나 App Engine 서비스를 사용하지 않고도 Google Cloud Storage에 파일을 업로드하는 쉬운 방법이 있습니까?

답변

3

App Engine을 사용하지 않는 것 같습니다. 그건 완전히 괜찮아. Google Cloud Storage는 App Engine에서 제대로 작동하지만 꼭 필요한 것은 아닙니다. App Engine을 사용해야하는 appengine-gcs-client 패키지에는 App Engine이 필요합니다.

대신 google-api-services-storage가 필요합니다. 여기에 자바와 메이븐과 함께 GCS JSON API를 사용하는 예제있다

: 여기

https://cloud.google.com/storage/docs/json_api/v1/json-api-java-samples

+0

감사를 바랍니다. 이 json-api로 시도하고 놀고 난 후에 나는 되돌아 올 것이다! +1에 대한 빠른 도움말 : – DominikAngerer

3

데이터와 사진을 다시 얻을 내 서블릿 APP 엔진의 코드는 다음 데이터 저장소에 저장하고 클라우드 스토리지. 오늘 오후 또는 다음 주 - 이 예를 들어, 내가 한 번 봐 것입니다 .. 그것은 당신을 도울

@Override 
      public void doPost(HttpServletRequest req, HttpServletResponse res) 
       throws ServletException, IOException {    

      //Get GCS service 
      GcsService gcsService = GcsServiceFactory.createGcsService(); 

      //Generate string for my photo 
      String unique = UUID.randomUUID().toString();  

      //Open GCS File 
      GcsFilename filename = new GcsFilename(CONSTANTES.BUCKETNAME, unique+".jpg");    

      //Set Option for that file 
      GcsFileOptions options = new GcsFileOptions.Builder() 
        .mimeType("image/jpg") 
        .acl("public-read") 
        .build(); 


      //Canal to write on it 
      GcsOutputChannel writeChannel = gcsService.createOrReplace(filename, options); 

      //For multipart support 
      ServletFileUpload upload = new ServletFileUpload(); 

      //Trying to create file 
      try { 


       FileItemIterator iterator = upload.getItemIterator(req); 


        while (iterator.hasNext()) { 
         FileItemStream item = iterator.next();      
         InputStream stream = item.openStream(); 

         if (item.isFormField()) {      

          String texte_recu_filtre = IOUtils.toString(stream);      

          if (item.getFieldName().equals("Type")){ 
           Type=Integer.parseInt(texte_recu_filtre);       
          }else if (item.getFieldName().equals("DateHeure")){ 
           DateHeure=texte_recu_filtre; 
          }else if (item.getFieldName().equals("NumPort")){ 
           NumPort=texte_recu_filtre; 
          }else if (item.getFieldName().equals("CodePays")){ 
           CodePays=Integer.parseInt(texte_recu_filtre); 
          } 

         } else {      


          byte[] bytes = ByteStreams.toByteArray(stream); 

          try { 
           //Write data from photo 
           writeChannel.write(ByteBuffer.wrap(bytes));        

          } finally {        

           writeChannel.close(); 
           stream.close(); 

           /
           res.setStatus(HttpServletResponse.SC_CREATED); 

           res.setContentType("text/plain"); 
          }   
         }   
        } 



       Key<Utilisateur> cleUtilisateur = Key.create(Utilisateur.class, NumPort);    


       Utilisateur posteur = ofy().load().key(cleUtilisateur).now();    

       //Add to datatstore with Objectify 
       Campagne photo_uploaded = new Campagne(CONSTANTES.chaineToDelete+unique+".jpg", Type, date_prise_photo, 0, cleUtilisateur, CodePays, posteur.getliste_contact()); 

       ofy().save().entity(photo_uploaded).now();       


       } catch (FileUploadException e) { 

        e.printStackTrace(); 
       }    

     } 
+0

필 필, 문제는 내가 App Engine을 사용하지 않고 있으며 현재는 사용하고 싶지 않다는 것입니다. 문제는이 예를 실행하려면 Google의 App Engine을 사용해야한다는 것입니다. -하지만 고마워. – DominikAngerer