【问题标题】:Save Image in Google Cloud Storage将图像保存在 Google Cloud Storage 中
【发布时间】:2014-11-06 10:45:29
【问题描述】:

我目前正在开展一个项目,我们应该可以将文件上传到 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.

在谷歌搜索了很多之后,阅读文档甚至在 bing 中搜索我发现了这个条目:The API package 'channel' or call 'CreateChannel()' was not found

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

【问题讨论】:

    标签: java google-cloud-storage client-library


    【解决方案1】:

    听起来您没有使用 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 的快速帮助:)
    【解决方案2】:

    这是我的 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();
                    }               
    
             } 
    

    【讨论】:

    • 谢谢菲尔,问题是我没有使用 App Engine,现在我不想使用它 - 我也尝试过像你那样使用它,但问题是运行这个例子我需要使用谷歌的 App Engine。 - 但谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-08-11
    • 2014-06-16
    • 1970-01-01
    • 2018-05-23
    • 2018-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多