Search code examples
objective-cxcode6nsmutableurlrequest

Objective c uploading multiple files to server


In my app i need to upload a audio file and xml file to server. I successfully post audio file. But i don’t know how to send two files in parallel. Anyone please help me.

NSString *soundFilePath = [[self GetDocumentDirectory]
                               stringByAppendingPathComponent:audioDet.audioName];
    NSMutableData *file1Data = [[NSMutableData alloc] initWithContentsOfFile:soundFilePath];

        //uploads/
        NSString *urlString = @"http://192.168.1.99/projects/fileUpload/upload.php";
        NSString *filename = audioDet.audioName;
        NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init] ;
        [request setURL:[NSURL URLWithString:urlString]];
        [request setHTTPMethod:@"POST"];

        NSString *boundary = @"---------------------------14737809831466499882746641449";
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
        [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
        [request setValue:@"Crystal" forHTTPHeaderField:@"ClientApp"];
        [request setValue:@"1.0" forHTTPHeaderField:@"ClientVersion"];
        [request setValue:@"617272656E64616C65445652" forHTTPHeaderField:@"ClientCredential"];
        [request setValue:audioDet.audioName forHTTPHeaderField:@"Target-file-name"];
        [request setValue:[NSString stringWithFormat:@"%@",audioDet.audioFileSize] forHTTPHeaderField:@"Target-file-length"];
        NSMutableData *postbody = [NSMutableData data];
        [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
      //  NSString * value1 = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; name=\"%@\"\r\n", filename];

        [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", filename ] dataUsingEncoding:NSUTF8StringEncoding]];
        [postbody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [postbody appendData:[NSData dataWithData:file1Data]];
        [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [request setHTTPBody:postbody];

        NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

Thanks, AKS


Solution

  • Store the multiple files in an array and iterate the same using for loop to send multiple files in the server.