javagoogle-cloud-storageclient-library

Save Image in Google Cloud Storage


I'm currently working on a project where we should have the possibility to upload files to the Google Cloud Storage. So we created an Bucket and I added the Maven dependency to my local "normal" application:

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

Then I started to read a local file and tried to push that to the Google Cloud Storage in a simply main:

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

My copy method looks like this:

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

All I get from that is this:

The API package 'file' or call 'Create()' was not found.

After searching a lot in google, reading documentations even searching in bing i found this entry: The API package 'channel' or call 'CreateChannel()' was not found

It says that there is no way to use the appengine.tools -> gcs-client without such an AppEngine App. But is there an easy way to upload files to the Google Cloud Storage without to be forced on using the AppEngine service?


Solution

  • It sounds like you're not using App Engine. That's completely fine. Google Cloud Storage can work fine with App Engine, but it by no means requires it. The appengine-gcs-client package you're trying to use does require App Engine, though.

    Instead, you want google-api-services-storage.

    There's an example of using the GCS JSON API with Java and Maven here:

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