I would like to upload file to HTTP server. I do it like that right now:
NSString *boundary = @"*****";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://someUploadScript.php"]];
[request setHTTPMethod:@"POST"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];
[request setValue:@"Keep-Alive" forHTTPHeaderField: @"Connection"];
dispatch_async(queue, ^{
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"video.mp4\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
NSString* outputPath = @"somePathToFile";
NSData *data = [NSData dataWithContentsOfFile:outputPath];
[postbody appendData:data];
[postbody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
previousBytesWritten = 0;
connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
});
I would like to send some additional data in eg. filed "user" with "userId" value. I would like to send some kind of array like:
video[user] = "userId"
video[file] = //file bytes
I know I can do like this using HTTP multipartform-data but I really don know how and I don't understand how it works. Can some one explain me how can I do that and how it works?
Try something like this:
Also dont forget to add 'Content-Length' http header field in your request.
You can use my library for such network request:
The delegate is set for notification about upload progress.
AFNetowrking is Handy solution for today. Can achieve this easily.
For iOS 6 and above
If project is to iOS 7 and above better to use.
above code samples are from the library documentation. Which can be found at https://github.com/AFNetworking/AFNetworking