要通过签名URL将文件上传到Google Cloud存储,您可以使用以下代码示例:
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;
public class GCSUploader {
private static final String BUCKET_NAME = "your-bucket-name";
private static final String OBJECT_NAME = "your-object-name";
private static final String CREDENTIALS_PATH = "/path/to/your/credentials.json";
public static void uploadFileWithSignedUrl() throws IOException {
// 从JSON凭据文件中获取Google Cloud Storage凭据
GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(CREDENTIALS_PATH));
// 设置Google Cloud Storage选项
StorageOptions options = StorageOptions.newBuilder().setCredentials(credentials).build();
Storage storage = options.getService();
// 创建用于上传的BlobInfo对象
BlobInfo blobInfo = BlobInfo.newBuilder(BUCKET_NAME, OBJECT_NAME).build();
// 生成签名URL
String signedUrl = storage.signUrl(blobInfo, 5, TimeUnit.MINUTES);
// 上传文件
Path filePath = Paths.get("/path/to/your/local/file");
byte[] fileBytes = Files.readAllBytes(filePath);
Blob blob = storage.create(blobInfo, fileBytes);
System.out.println("文件上传成功!签名URL: " + signedUrl);
}
public static void main(String[] args) {
try {
uploadFileWithSignedUrl();
} catch (IOException e) {
e.printStackTrace();
}
}
}
请确保替换示例代码中的以下值:
your-bucket-name
:您的Google Cloud存储桶名称。your-object-name
:要上传的对象在存储桶中的名称。/path/to/your/credentials.json
:您的Google Cloud凭据JSON文件的路径。/path/to/your/local/file
:要上传的本地文件的路径。您可以在Google Cloud Console中创建一个存储桶,并在其中上传文件,然后使用上述代码示例生成签名URL并将文件上传到存储桶中。