简体   繁体   中英

File upload directly from SwiftUI to S3

I have read several articles and examples about how to upload a file (specifically a UIImage in my case) directly to a S3 bucket that I own. I seem to be missing something.

I made the S3 bucket public, and I am otherwise able to make GET and POST requests to the EC2 instance I own in the same AWS region. I used to use Digital Ocean, and this is my first project on AWS. This is also my first real project in Xcode.

import Foundation
import AWSS3
import ClientRuntime
import AWSClientRuntime
import SwiftUI

let bucketName = "path to s3 resource name arn:aws:s3..."
let objName = "TestObject"
let data = image.jpegData(compressionQuality: 0.9) // image is a UIImage from an image picker

//this completes without issue

        do {
            let client = try await S3Client(region: "region_name")
        } catch {
            print("ERROR: ", dump(error, name: "Initializing s3 client"))
            exit(1)
        }

        let key = "filename.jpg"
        let dataStream = ByteStream.from(data: data)
        print("set dataStream")
        let input = PutObjectInput(
            body: dataStream,
            bucket: bucket, // 
            key: key 
        )
        // client.putObject fails. "Some failure in putObject" is printing to the console
        do {
            let res = try await client.putObject(input: input)
        } catch {
            print("Some failure in putObject")
        }


There isn't really an error that is thrown. At minimum, can someone help me figure out how to find out why putObject fails? From my reading, the putObject function requires that IAM permissions be set, but I would think that would only matter if the bucket were private and I were attempting to write the files from the ec2 instance. Is there some other configuration that is commonly missed?

You can not upload any files to bucket without credentials. Bucket public means public read not public upload.

This is not best practice but for your test you can with access_key and secret_key on swift side.

Init client with AWSClientRuntime.AWSClientConfiguration config

See also: https://github.com/awslabs/aws-sdk-swift/blob/main/AWSClientRuntime/Sources/Auth/AWSCredentialsProvider.swift#L33

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM