以下是如何将文件从端点保存到云存储并返回用于下载该文件的 URL。
1/ 在项目控制台中激活 Google Cloud Storage
2/ 在您的 Cloud Storage 实例中创建一个存储桶,名称为bucketName。可选:您可以设置此存储桶的访问权限。
3/ 在您的端点类中,创建一个 gcp 服务,如下所示:
private final GcsService gcsService = GcsServiceFactory.createGcsService(new RetryParams.Builder()
.initialRetryDelayMillis(10)
.retryMaxAttempts(10)
.totalRetryPeriodMillis(15000)
.build());
4/ 在您的方法中,创建一个 ByteArrayOutputStream:
ByteArrayOutputStream os = new ByteArrayOutputStream();
5/ 从 ByteArrayOutputStream 创建打印机
6/ 然后执行以下操作:
ByteBuffer buf = ByteBuffer.wrap(os.toByteArray());
GcsFilename gcsfileName = new GcsFilename(bucketName, bucketFileName);
//bucketFileName = your file name
GcsFileOptions options = new GcsFileOptions.Builder().mimeType("text/plain").build();
GcsOutputChannel outputChannel = gcsService.createOrReplace(gcsfileName, options);
outputChannel.write(buf);
outputChannel.close();
7/ 然后,您的文件应保存到云存储:您只需在字符串包装器中返回 url 即可打开它。查看以下文档来决定使用哪个 URL(取决于用户是否需要进行身份验证,请参阅“用户被授予对对象的读取访问权限”部分)https://cloud.google.com/storage/docs/cloud-console#_accessing https://cloud.google.com/storage/docs/cloud-console#_accessing