简体   繁体   English

文件直接从SwiftUI上传到S3

[英]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.我已经阅读了几篇关于如何将文件(在我的例子中是 UIImage)直接上传到我拥有的 S3 存储桶的文章和示例。 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.我公开了 S3 存储桶,否则我可以向我在同一 AWS 区域中拥有的 EC2 实例发出 GET 和 POST 请求。 I used to use Digital Ocean, and this is my first project on AWS.我以前用过Digital Ocean,这是我在AWS上的第一个项目。 This is also my first real project in Xcode.这也是我在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. Bucket public 表示公开读取而不是公开上传。

This is not best practice but for your test you can with access_key and secret_key on swift side.这不是最佳实践,但对于您的测试,您可以在 swift 端使用 access_key 和 secret_key。

Init client with AWSClientRuntime.AWSClientConfiguration config使用AWSClientRuntime.AWSClientConfiguration配置初始化客户端

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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