I want to develop a java-application (for pc) which can upload any picture to Google Cloud Storage. Although I have spent my whole evening on searching for a solution, I don
@Override
public String uploadImage(String fileName , String filePath,String fileType) throws IOException {
Bucket bucket = getBucket("sample-bucket");
InputStream inputStream = new FileInputStream(new File(filePath));
Blob blob = bucket.create(fileName, inputStream, fileType);
log.info("Blob Link:"+blob.getMediaLink());
return blob.getMediaLink();
}
private Bucket getBucket(String bucketName) throws IOException {
GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(CREDENTIALS_PATH))
.createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));
Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();
Bucket bucket = storage.get(bucketName);
if (bucket == null) {
throw new IOException("Bucket not found:"+bucketName);
}
return bucket;
}
CREDENTIALS_PATH , Download when setting the service account , make sure the the user have the permission to upload the image in the bucket .
You can public your file, and then the media link of the blob can access anywhere.
https://cloud.google.com/storage/docs/access-control/making-data-public
This is my solution.
try {
FileInputStream serviceAccount =
new FileInputStream("firebaseKey/serviceAccountKey.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://xxxxx.firebaseio.com")
.build();
FirebaseApp fireApp = FirebaseApp.initializeApp(options);
StorageClient storageClient = StorageClient.getInstance(fireApp);
InputStream testFile = new FileInputStream(file.getPath());
String blobString = "NEW_FOLDER/" + "FILE_NAME.jpg";
Blob blob = storageClient.bucket("xxxxxx.appspot.com")
.create(blobString, testFile , Bucket.BlobWriteOption.userProject("xxxxxxx"));
blob.getStorage().createAcl(blob.getBlobId(), Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER));
System.out.println(blob.getMediaLink());
} catch (Exception e){
e.printStackTrace();
}
There's a lovely Java API for using Google Cloud, including Storage: http://googlecloudplatform.github.io/google-cloud-java/0.10.0/index.html
Here's an example desktop application that uses this library to upload and download files: https://github.com/GoogleCloudPlatform/google-cloud-java/blob/master/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/StorageExample.java
Google Cloud Storage has quite a bit of documentation, guides, and tutorials. Here's the root of it all: https://cloud.google.com/storage/docs/