iosobjective-cfile-upload

iPhone upload multipart file using AFNetworking


In my iOS app I want to upload file with the java API using NSMutableURLRequest for multipart file. here is the form which shows parameter.

  <form action="API_URL" encType='multipart/form-data' method=post>
            <input type=file name="files">
            <input type=submit value="Upload Attempt Files">

EDIT form2

       <form action='URL' method="post" encType='multipart/form-data'>
<input name="key1" value='123'>
<input name="key2" value='asdf'>
<input name="key3" value='qwerty'>
<input name="key4" value='aaa'>
<input name="key5" value='aaa'>
<input name="key6" value='false'>
<input type="file"  name="files">
<input type=submit value="Create Forum Posts">
   </form>        

How can I achieve that?

This Question shows how to upload multipart file using AFNetworking in iOS(objective c). But I am not getting how to put parameter as per form I am using.


Solution

  • Looking at your HTML, the name of your <input type=file> is files, and thus, you would use @"files" as the name parameter to the appendPartWithFileData method. For example, with AFNetworking 3.x:

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData
                                    name:@"files"
                                fileName:photoName mimeType:@"image/jpeg"];
    
        [formData appendPartWithFormData:[key1 dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"key1"];
    
        [formData appendPartWithFormData:[key2 dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"key2"];
    
        // etc.
    } progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"Response: %@", responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    

    (For AFNetworking 1.x and 2.x syntax, see the revision history of this answer.)