Upload image to Google Cloud Storage (Java)

后端 未结 3 1872
梦谈多话
梦谈多话 2021-01-15 16:11

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

3条回答
  •  时光取名叫无心
    2021-01-15 16:51

      @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 .

提交回复
热议问题