How to download a file from Google Cloud Storage with Java?

后端 未结 3 685
不知归路
不知归路 2020-12-10 19:58

I\'m developping an application that provides users with an interface where they can download files from our Google Cloud Storage. I wrote unit tests and I could connect to

相关标签:
3条回答
  • 2020-12-10 20:11

    With the latest libraries :

    Storage storage = StorageOptions.newBuilder()
                .setProjectId(projectId)
                .setCredentials(GoogleCredentials.fromStream(new FileInputStream(serviceAccountJSON)))
                .build()
                .getService();
    Blob blob = storage.get(BUCKET_URL, RELATIVE_OBJECT_LOCATION);
    ReadChannel readChannel = blob.reader();
    FileOutputStream fileOutputStream = new FileOutputStream(outputFileName);
    fileOutputStream.getChannel().transferFrom(readChannel, 0, Long.MAX_VALUE);
    fileOutputStream.close();
    
    0 讨论(0)
  • 2020-12-10 20:15

    As you say, currently you're downloading the metadata. You need to use media download to download the object's data.

    Take a look at the sample Java code here: https://developers.google.com/storage/docs/json_api/v1/objects/get

    That is the simplest method, using getMediaHttpDownloader().

    There is more info on media and the other method, resumable download, here: https://code.google.com/p/google-api-java-client/wiki/MediaDownload

    0 讨论(0)
  • 2020-12-10 20:35

    @AnandMohan is correct. You just have to make copy on "tmp" folder because all the locations are read only, just "tmp" is writable. Check below:

        Storage storage = StorageOptions.newBuilder().setProjectId(PROJECT_ID).build().getService();
        Blob blob = storage.get(BUCKET_NAME, fileName);
        ReadChannel readChannel = blob.reader();
        File file = new File("/tmp/" + FILE_NAME);
        FileOutputStream fileOuputStream = new FileOutputStream(file);
        fileOuputStream.getChannel().transferFrom(readChannel, 0, Long.MAX_VALUE);
        fileOuputStream.close();
        // Now file is ready to send whereever you want
    
    0 讨论(0)
提交回复
热议问题