简体   繁体   中英

AFNetworking Upload image from iOS to API

I'm having trouble uploading an image with data. This code allows me to upload data just fine:

    NSURL *url = [NSURL URLWithString:@"my_base_url"];
AFHTTPClient *client = [[AFHTTPClient alloc]initWithBaseURL:url];

//depending on what kind of response you expect.. change it if you expect XML
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];

NSDictionary *params = [[NSDictionary alloc]initWithObjectsAndKeys:
                        _topicText.text,@"Topic",
                        @"1",@"Category",
                        @"",@"MainMedia",
                        @"1",@"Creator",
                        nil];
[client postPath:@"apidebate/debates" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
    //

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"failure");
}];

However, I've been unsuccessful in trying to upload an image with that data:

    NSURL *url = [NSURL URLWithString:@"my_base_url"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"MainMedia"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:imageData name:@"MainMedia" fileName:@"MainMedia" mimeType:@"image/jpeg"];
}];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation start];

What in the work could I be doing wrong??

Edit (adding server code)

The back-end is Codeigniter with the REST client Phil Sturgeon built (great library, btw). I'm almost sure it's not the server code though, as the first line of this method sends me an email. When I attempt to use the above code to post an image, the email never comes. So, it seems it's nt even getting to the endpoint.

//CONTROLLER FROM API
function debates_post()
{
    mail('myemailaddress@gmail.com', 'Test', 'Posted');
    $tmp_dir = "images/posted/";

    if(isset($_FILES['MainMedia'])){
        $SaniFileName = preg_replace('/[^a-zA-Z0-9-_\.]/','', basename($_FILES['MainMedia']['name']));

        $file = $tmp_dir . $SaniFileName;
        move_uploaded_file($_FILES['MainMedia']['tmp_name'], $file);
    }
    else
        $SaniFileName = NULL;

    $data = array('Topic'=>$this->post('Topic'), 'MainMedia'=>$this->post('MainMedia'), 'Category'=>$this->post('Category'), 'Creator'=>$this->post('Creator'));
    $insert = $this->debate->post_debate($this->post('Topic'), $SaniFileName, $this->post('Category'), $this->post('Creator'));
    if($insert){
        $message = $this->db->insert_id();
    }
    else{
        $message = 'Insert failed';
    }

    $this->response($message, 200);
}

//MODEL
function post_debate($Topic=NULL, $MainMedia='', $Category=NULL, $Creator=NULL){
    $MainMedia = ($MainMedia)?$MainMedia:'';
    $data = array(
                    'Topic' => $Topic,
                    'MainMedia' => $MainMedia,
                    'Category' => $Category,
                    'Creator' => $Creator,
                    'Created' => date('Y-m-d h:i:s')
                );
    return $this->db->insert('debate_table', $data);
}

ok, so apparently using fileName:@"MainMedia" for the filename left me with an extension-less uploaded file which was causing an error server-side. Adding ".jpg" to "MainMedia.jpg" fixed this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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