Last active
July 12, 2018 15:34
-
-
Save frangarcia/4c6f65bca1c72fb61478273f0ac54b55 to your computer and use it in GitHub Desktop.
Example of how to upload images into a Google Cloud Storage with Groovy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Grapes([ | |
@Grab(group='com.google.cloud', module='google-cloud-storage', version='1.31.0'), | |
@Grab(group='com.google.auth', module='google-auth-library-credentials', version='0.9.1') | |
]) | |
import com.google.cloud.storage.Bucket; | |
import com.google.cloud.storage.BucketInfo; | |
import com.google.cloud.storage.Storage; | |
import com.google.cloud.storage.Storage.BucketGetOption; | |
import com.google.cloud.storage.Blob; | |
import com.google.cloud.storage.StorageOptions; | |
import com.google.auth.oauth2.GoogleCredentials; | |
import com.google.api.gax.paging.Page; | |
import com.google.cloud.storage.Bucket.BlobWriteOption; | |
import com.google.cloud.storage.Storage.PredefinedAcl; | |
String serviceAccountJSON = "<PATH_TO_YOUR_JSON_FILE_WITH_CREDENTIALS>" | |
Storage storage = StorageOptions.newBuilder() | |
.setProjectId("<YOUR_PROJECT_ID>") | |
.setCredentials(GoogleCredentials.fromStream(new FileInputStream(serviceAccountJSON))) | |
.build() | |
.getService(); | |
final String BUCKET_NAME = "<YOUR_BUCKET_NAME>" | |
Bucket bucket = storage.get(BUCKET_NAME) | |
Page<Blob> blobs = bucket.list() | |
for (Blob blob : blobs.iterateAll()){ | |
println """{ | |
"name":"${blob.name}", | |
"size":"${blob.size}", | |
"downloadUrl":"${blob.mediaLink}", | |
"selfLink":"${blob.selfLink}" | |
"storageClass":"${blob.storageClass}" | |
"publicUrl":"https://storage.googleapis.com/${BUCKET_NAME}/${blob.name}" | |
}""" | |
} | |
//Uploading a file | |
InputStream content = new ByteArrayInputStream("Hello, World!".getBytes("UTF8")); | |
Blob blob = bucket.create("filename.txt", content); | |
storage.update(blob.toBuilder().setMetadata(["Content-Type":"text/plain"]).build()) | |
String folderLocation = "<A_FOLDER_WITH_SOME_IMAGES>" | |
//Uploading an image | |
String fileName1 = "Barney.jpg" | |
FileInputStream fis1 = new FileInputStream(new File(folderLocation+fileName1)) | |
bucket.create("Barney.jpg", fis1, URLConnection.guessContentTypeFromName(fileName1)?:URLConnection.guessContentTypeFromStream(fis1), Bucket.BlobWriteOption.predefinedAcl(Storage.PredefinedAcl.PUBLIC_READ)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment