Google cloud storage 将文件上载到谷歌云存储

Google cloud storage 将文件上载到谷歌云存储,google-cloud-storage,Google Cloud Storage,我正在不同的云存储上做一些实验,我有文件(图像2MB大小)。我想测试上传和下载到不同云供应商的速度。 谷歌上的大多数例子都是使用html表单,这不是我想要的,但对我来说,文件是确定的,所以我需要运行代码几天,然后离开它,以查看每小时速度之间的差异 我已经设法在AmazonS3上测试了它,但是我找不到如何在Google上上传它,下面的代码是我想做的一个例子,我没有上传的功能 package main.java; //[START all] /* * Copyright (c) 2014

我正在不同的云存储上做一些实验,我有文件(图像2MB大小)。我想测试上传和下载到不同云供应商的速度。 谷歌上的大多数例子都是使用html表单,这不是我想要的,但对我来说,文件是确定的,所以我需要运行代码几天,然后离开它,以查看每小时速度之间的差异 我已经设法在AmazonS3上测试了它,但是我找不到如何在Google上上传它,下面的代码是我想做的一个例子,我没有上传的功能

    package main.java;
//[START all]
/*
 * Copyright (c) 2014 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.DataStoreFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.StorageScopes;
import com.google.api.services.storage.model.Bucket;
import com.google.api.services.storage.model.StorageObject;


import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Main class for the Cloud Storage API command line sample.
 * Demonstrates how to make an authenticated API call using OAuth 2 helper classes.
 */
public class StorageSample {

  /**
   * Be sure to specify the name of your application. If the application name is {@code null} or
   * blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0".
   */
  private static final String APPLICATION_NAME = "seraphic-beacon-659";
  private static final String BUCKET_NAME = "afhabucket";

  /** Directory to store user credentials. */
  private static final java.io.File DATA_STORE_DIR =
      new java.io.File(System.getProperty("user.home"), ".store/storage_sample");

  /**
   * Global instance of the {@link DataStoreFactory}. The best practice is to make it a single
   * globally shared instance across your application.
   */
  private static FileDataStoreFactory dataStoreFactory;

  /** Global instance of the JSON factory. */
  private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

  /** Global instance of the HTTP transport. */
  private static HttpTransport httpTransport;

  private static Storage client;

  /** Authorizes the installed application to access user's protected data. */
  private static Credential authorize() throws Exception {
    // Load client secrets.
        GoogleClientSecrets clientSecrets = null;
        try {
        clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
            new InputStreamReader(StorageSample.class.getResourceAsStream("../resources/client_secrets.json")));
        if (clientSecrets.getDetails().getClientId() == null ||
                clientSecrets.getDetails().getClientSecret() == null) {
                throw new Exception("client_secrets not well formed.");
        }
        } catch (Exception e) {
                System.out.println("Problem loading client_secrets.json file. Make sure it exists, you are " + 
                                   "loading it with the right path, and a client ID and client secret are " +
                                   "defined in it.\n" + e.getMessage());
                System.exit(1);
        }

    // Set up authorization code flow.
    // Ask for only the permissions you need. Asking for more permissions will
    // reduce the number of users who finish the process for giving you access
    // to their accounts. It will also increase the amount of effort you will
    // have to spend explaining to users what you are doing with their data.
    // Here we are listing all of the available scopes. You should remove scopes
    // that you are not actually using.
    Set<String> scopes = new HashSet<String>();
    scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);
    scopes.add(StorageScopes.DEVSTORAGE_READ_ONLY);
    scopes.add(StorageScopes.DEVSTORAGE_READ_WRITE);

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        httpTransport, JSON_FACTORY, clientSecrets, scopes)
        .setDataStoreFactory(dataStoreFactory)
        .build();
    // Authorize.
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
  }

  public static void main(String[] args) {
    try {
      // Initialize the transport.
      httpTransport = GoogleNetHttpTransport.newTrustedTransport();

      // Initialize the data store factory.
      dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

      // Authorization.
      Credential credential = authorize();

      // Set up global Storage instance.
      client = new Storage.Builder(httpTransport, JSON_FACTORY, credential)
          .setApplicationName(APPLICATION_NAME).build();

      // Get metadata about the specified bucket.
      Storage.Buckets.Get getBucket = client.buckets().get(BUCKET_NAME);
      getBucket.setProjection("full");
      Bucket bucket = getBucket.execute();
      System.out.println("name: " + BUCKET_NAME);
      System.out.println("location: " + bucket.getLocation());
      System.out.println("timeCreated: " + bucket.getTimeCreated());
      System.out.println("owner: " + bucket.getOwner());

//==========================


     // upload function


//=============================


    } catch (IOException e) {
      System.err.println(e.getMessage());
    } catch (Throwable t) {
      t.printStackTrace();
    }
    System.exit(1);
  }
}
//[END all]
package main.java;
//[全部启动]
/*
*版权所有(c)2014谷歌公司。
*
*根据Apache许可证2.0版(以下简称“许可证”)获得许可;您不能使用此文件,除非
*符合许可证的要求。您可以通过以下方式获得许可证副本:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*除非适用法律要求或书面同意,否则根据许可证分发的软件
*在“按原样”的基础上分发,无任何形式的保证或条件,无论是明示的还是明示的
*或者暗示。请参阅下面的许可证,了解管理权限和限制的特定语言
*执照。
*/
导入com.google.api.client.auth.oauth2.Credential;
导入com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
导入com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
导入com.google.api.client.googleapis.auth.oauth2.googleaauthorizationcodeflow;
导入com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
导入com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
导入com.google.api.client.http.HttpTransport;
导入com.google.api.client.json.JsonFactory;
导入com.google.api.client.json.jackson2.JacksonFactory;
导入com.google.api.client.util.store.DataStoreFactory;
导入com.google.api.client.util.store.FileDataStoreFactory;
导入com.google.api.services.storage.storage;
导入com.google.api.services.storage.StorageScopes;
导入com.google.api.services.storage.model.Bucket;
导入com.google.api.services.storage.model.StorageObject;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.util.HashSet;
导入java.util.List;
导入java.util.Set;
/**
*云存储API命令行示例的主类。
*演示如何使用OAuth 2帮助程序类进行经过身份验证的API调用。
*/
公共类存储示例{
/**
*请确保指定应用程序的名称。如果应用程序名称为{@code null}或
*空白,应用程序将记录警告。建议的格式为“MyCompany ProductName/1.0”。
*/
专用静态最终字符串应用程序_NAME=“Serapic-beacon-659”;
私有静态最终字符串BUCKET_NAME=“afhabucket”;
/**用于存储用户凭据的目录*/
私有静态最终java.io.File数据\u存储\u目录=
新的java.io.File(System.getProperty(“user.home”),“.store/storage_sample”);
/**
*{@link DataStoreFactory}的全局实例。最佳做法是将其设置为单个
*应用程序中的全局共享实例。
*/
私有静态文件数据存储工厂数据存储工厂;
/**JSON工厂的全局实例*/
私有静态最终JsonFactory JSON_FACTORY=JacksonFactory.getDefaultInstance();
/**HTTP传输的全局实例*/
专用静态HttpTransport-HttpTransport;
专用静态存储客户端;
/**授权已安装的应用程序访问用户受保护的数据*/
私有静态凭据授权()引发异常{
//加载客户端机密。
GoogleClientSecrets clientSecrets=null;
试一试{
clientSecrets=GoogleClientSecrets.load(JSON_工厂,
新的InputStreamReader(StorageSample.class.getResourceAsStream(“../resources/client_secrets.json”);
如果(clientSecrets.getDetails().getClientId()==null||
clientSecrets.getDetails().getClientSecret()==null){
抛出新异常(“client_secrets格式不正确”);
}
}捕获(例外e){
System.out.println(“加载client_secrets.json文件时出现问题。请确保它存在,您是”+
使用正确的路径加载,客户端ID和客户端密码为+
“已在其中定义。\n”+e.getMessage());
系统出口(1);
}
//设置授权代码流。
//仅请求所需的权限。请求更多权限将
//减少完成为您提供访问权限的过程的用户数量
//这也会增加你的工作量
//你必须花时间向用户解释你在用他们的数据做什么。
//这里我们列出了所有可用的作用域。您应该删除作用域
//您实际上没有使用的。
Set scopes=new HashSet();
添加(StorageScopes.DEVSTORAGE\u FULL\u控件);
scopes.add(StorageScopes.DEVSTORAGE\u只读);
scopes.add(StorageScopes.DEVSTORAGE\u READ\u WRITE);
GoogleAuthorizationCodeFlow=新建GoogleAuthorizationCodeFlow.Builder(
httpTransport、JSON_工厂、客户端机密、作用域)
.setDataStoreFactory(数据存储工厂)
.build();
//授权。
返回新的AuthorizationCodeInstalledApp(流,新的LocalServerReceiver())。授权(“用户”);
}
公共静态void main(字符串[]args){
试一试{
//初始化传输。
httpTransport=GoogleNetHttpTransport.newTrustedTransport();
//初始化数据存储工厂。
dataStoreFactory=新文件dataStoreFactory(DATA\u STORE\u DIR);
//授权。
凭证=授权();
//设置全局存储实例。
client=new Storage.Builder(httpTransport、JSON\u工厂、凭证)
.setApplicationName(应用程序名称).build();
//获取元数据ab