Note
-
In a versioning-enabled bucket, OSS automatically generates a unique version ID for each new object. The version ID is returned in the x-oss-version-id response header.
-
In a bucket where versioning is suspended, the version ID of a new object is "null". If you upload an object with the same name, the new object overwrites the previous one. Only one version of an object can have a "null" version ID.
You can use the following code to perform a simple upload.
import AlibabaCloudOSS
import Foundation
@main
struct Main {
static func main() async {
do {
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
let region = "cn-hangzhou"
// Specify the bucket name.
let bucket = "yourBucketName"
// Optional. Specify the domain name used to access OSS. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
let endpoint: String? = nil
// Specify the object name, for example, my-object.txt.
let key = "yourKey"
// Load credentials from environment variables. You must set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables in advance.
let credentialsProvider = EnvironmentCredentialsProvider()
// Configure the OSS client.
let config = Configuration.default()
.withRegion(region) // Set the region.
.withCredentialsProvider(credentialsProvider) // Set the credentials provider.
// Set the endpoint.
if let endpoint = endpoint {
config.withEndpoint(endpoint)
}
// Create an OSS client instance.
let client = Client(config)
// Prepare the content to upload.
let content = "Hello, OSS!"
// Upload the object.
let result = try await client.putObject(
PutObjectRequest(
bucket: bucket,
key: key,
body: .data(content.data(using: .utf8)!)
)
)
// Print the result.
print("result:\n\(result)")
} catch {
// Catch and handle exceptions.
print("error:\n\(error)")
}
}
}