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 .