package com.stylefeng.guns.modular.system.util;
|
|
import com.google.cloud.WriteChannel;
|
import com.google.cloud.storage.BlobId;
|
import com.google.cloud.storage.BlobInfo;
|
import com.google.cloud.storage.Storage;
|
import com.google.cloud.storage.StorageOptions;
|
import org.springframework.web.multipart.MultipartFile;
|
|
import java.io.IOException;
|
import java.nio.ByteBuffer;
|
import java.nio.charset.StandardCharsets;
|
import java.nio.file.Paths;
|
|
/**
|
* google对象存储
|
* @author zhibing.pu
|
* @Date 2024/8/31 9:18
|
*/
|
public class GoogleCloudStorageUtil {
|
|
|
|
public static String upload(MultipartFile file){
|
// The ID of your GCP project
|
// String projectId = "your-project-id";
|
|
// The ID of your GCS bucket
|
// String bucketName = "your-unique-bucket-name";
|
|
// The ID of your GCS object
|
// String objectName = "your-object-name";
|
|
// The path to your file to upload
|
// String filePath = "path/to/your/file"
|
String fileName = file.getOriginalFilename();
|
String bucketName = "i-go";
|
Storage storage = StorageOptions.newBuilder().setProjectId("i-go-gcp").build().getService();
|
BlobId blobId = BlobId.of(bucketName, fileName);
|
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
|
|
// Optional: set a generation-match precondition to avoid potential race
|
// conditions and data corruptions. The request returns a 412 error if the
|
// preconditions are not met.
|
Storage.BlobWriteOption precondition;
|
if (storage.get(bucketName, fileName) == null) {
|
// For a target object that does not yet exist, set the DoesNotExist precondition.
|
// This will cause the request to fail if the object is created before the request runs.
|
precondition = Storage.BlobWriteOption.doesNotExist();
|
} else {
|
// If the destination already exists in your bucket, instead set a generation-match
|
// precondition. This will cause the request to fail if the existing object's generation
|
// changes before the request runs.
|
precondition =
|
Storage.BlobWriteOption.generationMatch(
|
storage.get(bucketName, fileName).getGeneration());
|
}
|
try {
|
storage.createFrom(blobInfo, file.getInputStream(), precondition);
|
System.out.println(
|
"File uploaded to bucket " + bucketName + " as " + fileName);
|
return "https://storage.cloud.google.com/" + bucketName + "/" + fileName + "?authuser=1";
|
} catch (IOException e) {
|
throw new RuntimeException(e);
|
}
|
}
|
|
|
|
}
|