Pu Zhibing
昨天 7bf07f46d7c39fa01b6d8abd860bd80c210d86cb
ManagementIGOTravel/guns-admin/src/main/java/com/stylefeng/guns/modular/system/util/GoogleCloudStorageUtil.java
@@ -1,5 +1,6 @@
package com.stylefeng.guns.modular.system.util;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.WriteChannel;
import com.google.cloud.storage.*;
import org.springframework.web.multipart.MultipartFile;
@@ -19,6 +20,10 @@
   
   
   public static String upload(MultipartFile file){
      // The ID of your GCP project
      // String projectId = "your-project-id";
      
@@ -31,9 +36,21 @@
      // The path to your file to upload
      // String filePath = "path/to/your/file"
      String fileName = file.getOriginalFilename();
      String projectId = "i-go-gcp";
      String bucketName = "i-go";
      Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
      String projectId = "i-go-cloud";
      String bucketName = "i-go-gcs-public";
        GoogleCredentials defaultCredentials = null;
        try {
            defaultCredentials = GoogleCredentials.getApplicationDefault();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        defaultCredentials.createScoped("https://www.googleapis.com/auth/cloud-platform");
      Storage storage = StorageOptions
            .newBuilder()
            .setProjectId(projectId)
            .setCredentials(defaultCredentials)
            .build()
            .getService();
      BlobId blobId = BlobId.of(bucketName, fileName);
      BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
      
@@ -57,7 +74,7 @@
         storage.createFrom(blobInfo, file.getInputStream(), precondition);
         System.out.println(
               "File uploaded to bucket " + bucketName + " as " + fileName);
         makeObjectPublic(projectId, bucketName, fileName);
         return "https://storage.googleapis.com/i-go/" + fileName;
      } catch (IOException e) {
@@ -82,5 +99,5 @@
      System.out.println(
            "Object " + objectName + " in bucket " + bucketName + " was made publicly readable");
   }
}