如何使用AWS SDK for Swift生成预签名URL?

5vf7fwbs  于 2023-10-15  发布在  Swift
关注(0)|答案(1)|浏览(129)

我正在使用Vapor构建一个服务器端Swift应用程序,并使用AWS SDK for Swift与S3进行交互。
我想为对象创建一个预签名的URL,以便用户可以下载和查看PDF文档。
如何使用SDK?我是否可以假设这在Swift SDK中还不可用?

nkkqxpd9

nkkqxpd91#

我是否可以假设这在Swift SDK中还不可用?
不,它在SDK中可用,但由于AWS SDK for Swift仍处于开发人员预览版,文档非常稀疏。
GetObjectInputPutObjectInput结构上使用.presignURL扩展来生成用于下载和上传S3对象的预签名URL。
下面是我写的一个完整的工作示例:

// main.swift

import AWSS3
import Foundation.NSTimeZone

let region = "eu-west-1"
let expirationInSeconds : TimeInterval = 3600;

let bucketName = "my-bucket-name"
let objectName = "my-object-name"

let putObjectRequest = PutObjectInput(bucket: bucketName, key: objectName)
let uploadUrl = try await putObjectRequest.presignURL(config: S3Client.S3ClientConfiguration(region: region), expiration: expirationInSeconds);

if let uploadUrl = uploadUrl {
    print("Upload URL: \(uploadUrl)")
}

let getObjectRequest = GetObjectInput(bucket: bucketName, key: objectName)
let downloadUrl = try await getObjectRequest.presignURL(config: S3Client.S3ClientConfiguration(region: region), expiration: expirationInSeconds);

if let downloadUrl = downloadUrl {
    print("Download URL: \(downloadUrl)")
}
// Package.swift

// swift-tools-version: 5.9

import PackageDescription

let package = Package(
    name: "PackageName",
    platforms: [.macOS(.v10_15), .iOS(.v13)],
    dependencies: [
        .package(url: "https://github.com/awslabs/aws-sdk-swift.git", from: "0.27.0")
    ],
    targets: [
        .executableTarget(
            name: "ExecutableName",
            dependencies: [
                .product(name: "AWSS3", package: "aws-sdk-swift")
            ],
            path: "Sources"
        )
    ]
)

输出量:
上传URL:https://my-bucket-name.s3.eu-west-1.amazonaws.com/my-object-name?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=xxxx%2Feu-west-1%2Fs3%2Faws4_request&X-Amz-Date=20231012T154344Z&X-Amz-SignedHeaders=host&X-Amz-Expires=3600&X-Amz-Signature=xxx
下载URL:https://my-bucket-name.s3.eu-west-1.amazonaws.com/my-object-name?Bucket=my-bucket-name&Key=my-object-name&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=xxx%2Feu-west-1%2Fs3%2Faws4_request&X-Amz-Date=20231012T154344Z&X-Amz-SignedHeaders=host&X-Amz-Expires=3600&X-Amz-Signature=xxx
程序以退出代码结束:0

相关问题