在Google云存储中保存图像

3

我目前正在一个项目中工作,我们需要将文件上传到Google Cloud Storage。因此,我们创建了一个Bucket,并将Maven依赖项添加到我的本地“普通”应用程序:

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

然后我开始读取本地文件,并尝试将其推送到Google Cloud Storage中:

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.

在谷歌上进行了大量搜索,阅读文档,甚至在必应上搜索后,我找到了这篇文章:API包“channel”或调用“CreateChannel()”未找到
它说没有办法使用appengine.tools -> gcs-client而无需使用AppEngine App。但是是否有一种简单的方法可以上传文件到Google Cloud Storage而不被迫使用AppEngine服务呢?
2个回答

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

         } 

谢谢Phil,问题是我没有使用App Engine,而且目前我也不想使用它 - 我也尝试过像你那样使用它,但问题是要运行这个示例,我需要使用Google的App Engine。- 不过还是谢谢。 - DominikAngerer

3

看起来你没有使用App Engine,这完全没问题。Google Cloud Storage可以与App Engine很好地配合使用,但这并不是必须的。然而,你正在尝试使用的appengine-gcs-client包需要App Engine。

相反,你需要用google-api-services-storage。

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

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


谢谢这个例子,我会在今天下午或下周看一下。尝试并玩弄这个json-api后,我会回来的!对于此刻的快速帮助,点赞+1 :) - DominikAngerer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接