如何使用 Google Cloud Endpoints 返回文件?

Cam*_*boy 0 java google-app-engine google-cloud-endpoints google-cloud-platform

我有一种方法可以生成带有一些数据库记录的 CSV 文件

    public static void generateCsvForAttendees( List<Attendee> attendeeList ) throws FileNotFoundException
    {
        PrintWriter pw = new PrintWriter(new File("test.csv"));

        StringBuilder sb = new StringBuilder();

        //Header
        sb.append( "Id" );
        sb.append( ',' );
        sb.append( "Name" );
        sb.append( ',' );
        sb.append( "Lastname" );
        sb.append('\n');

        //Content
        for( Attendee attendee: attendeeList )
        {
            sb.append( attendee.getId() );
            sb.append( ',' );
            sb.append( attendee.getUser().getName() );
            sb.append( ',' );
            sb.append( attendee.getUser().getLastname() );
            sb.append( '\n' );

        }

        pw.write(sb.toString());
        pw.close();
    }
Run Code Online (Sandbox Code Playgroud)

我希望该方法是一个端点,以便从任何类型的客户端(网络或移动设备)调用它来下载它。在Google Cloud Endpoint 文档中,没有关于 File 作为有效返回类型的内容。我如何创建和端点返回文件?

Ren*_*nec 5

以下是如何将文件从 Endpoint 保存到 Cloud Storage 并返回用于下载它的 URL。

1/ 在您的项目控制台中激活 Google Cloud Storage

2/ 在您的 Cloud Storage 实例中创建一个名为 bucketName 的 Bucket。可选:您可以设置此存储桶的访问权限。

3/ 在你的端点类中,创建一个 gcsService 如下:

private final GcsService gcsService = GcsServiceFactory.createGcsService(new RetryParams.Builder()
        .initialRetryDelayMillis(10)
        .retryMaxAttempts(10)
        .totalRetryPeriodMillis(15000)
        .build());
Run Code Online (Sandbox Code Playgroud)

4/ 在您的方法中,创建一个 ByteArrayOutputStream:

ByteArrayOutputStream os = new ByteArrayOutputStream();
Run Code Online (Sandbox Code Playgroud)

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();
Run Code Online (Sandbox Code Playgroud)

7/ 然后你的文件应该被保存到云存储:你只需要在一个字符串包装器中返回 URL 来打开它。查看以下文档以决定使用哪个 URL(取决于用户是否应通过身份验证,请参阅“用户被授予对对象的读取访问权限”部分)https://cloud.google.com/storage/docs/云控制台#_accessing