| | |
| | | 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; |
| | |
| | | |
| | | |
| | | public static String upload(MultipartFile file){ |
| | | |
| | | |
| | | |
| | | |
| | | // The ID of your GCP project |
| | | // String projectId = "your-project-id"; |
| | | |
| | |
| | | // 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(); |
| | | |
| | |
| | | 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) { |
| | |
| | | System.out.println( |
| | | "Object " + objectName + " in bucket " + bucketName + " was made publicly readable"); |
| | | } |
| | | |
| | | |
| | | } |