3

我目前正在开展一个项目,我们应该可以将文件上传到谷歌云存储。因此,我们创建了一个 Bucket,并将 Maven 依赖项添加到我的本地“普通”应用程序中:

<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 'file' or call 'Create()' was not found.

在谷歌搜索了很多之后,阅读文档甚至在 bing 中搜索我发现了这个条目:未找到 API 包 'channel' 或调用 'CreateChannel()'

它说appengine.tools -> gcs-client没有这样的 AppEngine 应用程序就无法使用。但是,有没有一种简单的方法可以将文件上传到 Google Cloud Storage,而无需强制使用 AppEngine 服务?

4

2 回答 2

3

听起来您没有使用 App Engine。那完全没问题。Google Cloud Storage 可以与 App Engine 一起正常工作,但绝不需要它。不过,您尝试使用的 appengine-gcs-client 软件包确实需要 App Engine。

相反,您需要 google-api-services-storage。

这里有一个将 GCS JSON API 与 Java 和 Maven 结合使用的示例:

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

于 2014-11-07T05:39:45.157 回答
3

这是我的 servlet APP Engine 的代码,它取回数据和照片,然后将它们存储到数据存储和云存储。希望对你有帮助。。

@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();
                }               

         } 
于 2014-11-07T08:57:40.593 回答