使用带有AFNetworking的S3预先发布的帖子

时间:2014-11-12 01:10:24

标签: ios amazon-s3 afnetworking

我正在尝试使用在我的服务器上生成的预签名表单将文件上传到S3。 api端点返回来自bucket.presigned_post的url和字段。我觉得这应该与示例使用的html表单相同,但它只是在没有响应的情况下超时。

NSLog(@"responseObject: %@", responseObject);
NSURL *uploadURL = [NSURL URLWithString:responseObject[@"upload_url"]];
NSLog(@"uploadURL: %@", uploadURL);
NSDictionary *uploadFields = responseObject[@"upload_fields"];
NSLog(@"uploadFields: %@", uploadFields);

AFHTTPSessionManager *client = [[AFHTTPSessionManager alloc] init];
[client POST:uploadURL.absoluteString parameters:uploadFields constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:imageData name:@"iPhone.png" fileName:@"file" mimeType:@"image/png"];
} success:^(NSURLSessionDataTask *task, id responseObject) {
    NSLog(@"upload responseObject: %@", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    NSLog(@"upload error: %@ %@", error, [[NSString alloc] initWithData:error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding]);
}];

该代码的输出(私人信息编辑):

uploadURL: https://**********.s3.amazonaws.com/
uploadFields: {
    AWSAccessKeyId = **********;
    "Cache-Control" = "max-age=300, private";
    Secure = true;
    acl = "public-read";
    key = "file_attachments/980191050/iPhone.png";
    policy = "**********";
    signature = "**********";
    "success_action_status" = 201;
}
upload error: Error Domain=NSURLErrorDomain Code=-1001 "The operation couldn’t be completed. (NSURLErrorDomain error -1001.)" UserInfo=0x7f92694caf10 {NSErrorFailingURLStringKey=https://thecity-dev.s3.amazonaws.com/, NSUnderlyingError=0x7f9269a80220 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1001.)", NSErrorFailingURLKey=https://thecity-dev.s3.amazonaws.com/}

1 个答案:

答案 0 :(得分:4)

我仍然不确定为什么AFNetworking无法正常工作,但我能够使用普通的NSURLConnection多部分表单来实现它。

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:uploadURL];
request.HTTPMethod = @"POST";
NSString *boundary = [NSString stringWithFormat:@"Boundary+%08X%08X", arc4random(), arc4random()];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *postbody = [NSMutableData data];

[uploadFields enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    [postbody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithFormat:@"%@\r\n", obj] dataUsingEncoding:NSUTF8StringEncoding]];
}];

[postbody appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", contentType] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:fileData];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if (connectionError != nil || ((NSHTTPURLResponse *)response).statusCode != 201) {
        if (failure != nil) {
            failure(task, connectionError);
        }
    } else {
        if (success != nil) {
            success(task, responseObject, [responseObject[@"id"] unsignedIntegerValue]);
        }
    }
}];