Alamofire和预先签名的网址上传对象

时间:2017-01-26 10:24:35

标签: ios amazon-web-services swift3 alamofire

目前我正在尝试使用Alamofire上传图片,亚马逊的示例实现如下:http://docs.aws.amazon.com/AmazonS3/latest/dev/PresignedUrlUploadObject.html

.NET版本代码:

private void UploadS3FileByPresignedUrl(string url, string localFile, string contentType)
    {
        using (var client = new HttpClient())
        {
            using (var stream = File.OpenRead(localFile))
            {
                //// Need to add contentType otherwise the StreamContent is "binary/octet-stream"
                var fileContent = new StreamContent(stream);
                fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
                var response = client.PutAsync(url, fileContent).Result;
                response.EnsureSuccessStatusCode();
            }

        }
    }

基本上我必须上传两个条件的图像:

  • 仅支持jpg图像文件。
  • 客户端获取上传URL后,需要使用内容类型为“image / jpeg”的HTTP PUT上传配置文件图像以下是.NET客户端的示例代码

我试图通过使用Alamofire来做到这一点,但我没有成功......

我正在使用swift 3和Alamofire 4,目前我有这个代码:

let image = UIImage(named: "Sky-Sunset")

        Alamofire.upload(multipartFormData:{ multipartFormData in
            multipartFormData.append(UIImageJPEGRepresentation(image!, 0.5)!, withName: "photo_path", fileName: "swift_file.jpeg", mimeType: "image/jpeg")},
                         usingThreshold:UInt64.init(),
                         to:".../my/profile/image/uploadurl",
                         method:.put,
                         headers:["Content-Type": "image/jpeg"],
                         encodingCompletion: { encodingResult in
                            switch encodingResult {
                            case .success(let upload, _, _):
                                upload.responseJSON { response in
                                    debugPrint(response)
                                }
                            case .failure(let encodingError):
                                print(encodingError)
                            }
        })

1 个答案:

答案 0 :(得分:0)

我建议使用AWS SDK for iOS,对于预先签名的网址支持,您可以按照文档@ https://docs.aws.amazon.com/mobile/sdkforios/developerguide/s3-pre-signed-urls.html

AWSS3PreSignedURLBuilder.default().getPreSignedURL(getPreSignedURLRequest).continueWith { (task:AWSTask<NSURL>) -> Any? in
    if let error = task.error as? NSError {
        print("Error: \(error)")
        return nil
    }

    let presignedURL = task.result
    print("Download presignedURL is: \(presignedURL)")

    Alamofire.upload(
       multipartFormData: { multipartFormData in
             multipartFormData.append(unicornImageURL, withName: "unicorn")
             multipartFormData.append(rainbowImageURL, withName: "rainbow")
       },
       to:presignedURL.absoluteString
       ...
    return nil
}