无法使用Alamofire直接上传到S3

时间:2016-01-21 17:43:49

标签: swift amazon-s3 alamofire

当我尝试使用以下代码上传图像时,我的请求超时了。奇怪的是,我甚至没有从S3获得失败回应。

[Request]: <NSMutableURLRequest: 0x12d958f20> { URL: https://[redacted].s3.amazonaws.com/96d5b0e9-4606-4a8d-bd22-8d30f840361a/611ad69fb0452bd7c806886cf6404b34-original.png?AWSAccessKeyId=[redacted]&Content-Type=image%2Fpng&Expires=1453484324&Signature=[redacted]&x-amz-acl=public-read }
[Response]: nil
[Data]: 0 bytes
[Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x12d946590 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=https://[redacted].s3.amazonaws.com/96d5b0e9-4606-4a8d-bd22-8d30f840361a/611ad69fb0452bd7c806886cf6404b34-original.png?AWSAccessKeyId=[redacted]&Content-Type=image%2Fpng&Expires=1453484324&Signature=[redacted]&x-amz-acl=public-read, NSErrorFailingURLKey=https://[redacted].s3.amazonaws.com/96d5b0e9-4606-4a8d-bd22-8d30f840361a/611ad69fb0452bd7c806886cf6404b34-original.png?AWSAccessKeyId=[redacted]&Content-Type=image%2Fpng&Expires=1453484324&Signature=[redacted]&x-amz-acl=public-read, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}
class func avatar ( uploadURL: String, avatar: UIImage, callback: ( String? ) -> ( ) ) {

    print( "Upload to \(uploadURL)" )
    Alamofire.upload( .POST, uploadURL, multipartFormData: { multipartFormData in
        if let imageData = UIImagePNGRepresentation(avatar) {
            multipartFormData.appendBodyPart( data: imageData, name: "file", fileName: "file.png", mimeType: "image/png" )
        }
    }, encodingCompletion: { encodingResult in
        print( "Encoded" )
        switch encodingResult {
        case .Success( let upload, _, _ ):
            print( "About to Upload" )
            upload.responseJSON { response in

                print( "Status code: \(response.response?.statusCode)" )
                print( response.debugDescription )

                switch response.result {
                case .Success:
                    callback( "url" )
                case .Failure:
                    callback( nil )
                }

            }
        case .Failure( let encodingError ):
            print( "===== ERROR ENCODING PNG =====" )
            print( encodingError )
        }
    } )

}

1 个答案:

答案 0 :(得分:0)

当我没有完全按照S3期望的格式获得多部分表单时,我遇到了类似的问题。而不是错误,它从未返回响应。

以下是我最终发送多部分表格

的文件部分的方法
multipartFormData.appendBodyPart(stream: NSInputStream(data: imageData),
                                 length: UInt64(imageData.length),
                                headers: ["Content-Disposition": "form-data; name=\"file\"",
                                          "Content-Type": "application/octet-stream"])