Use S3 Designated Post with AFNetworking

I am trying to upload a file to S3 using the form created on my server. The api endpoint returns the url and fields from bucket.presigned_post. It seems to me that this should be identical to the html form that this example uses, but it just shuts down without an answer.

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]);
}];

Exit from this code (private information edited):

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/}
+4
source share
1 answer

I'm still not sure why AFNetworking is not working, but I was able to get it to work using a simple form 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]);
        }
    }
}];
+4
source

All Articles