Skip to content

Instantly share code, notes, and snippets.

@digidigo
Created December 27, 2010 22:58
Show Gist options
  • Save digidigo/756671 to your computer and use it in GitHub Desktop.
Save digidigo/756671 to your computer and use it in GitHub Desktop.
NSString *urlString = @"http://yourserver.com/upload_huge_file";
NSString *filename = @"filename";
NSString * pathToHugeFileToPost = @"hugeFile";
NSMutableURLRequest * request= [[[NSMutableURLRequest alloc] init] autorelease];
[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"];
NSString * tempFile = [NSTemporaryDirectory() stringByAppendingPathComponent: [NSString stringWithFormat: @"%.0f.%@", [NSDate timeIntervalSinceReferenceDate] * 1000.0, @".data"]];
if(![[NSFileManager defaultManager] fileExistsAtPath: tempFile]) {
[[NSFileManager defaultManager] createFileAtPath: tempFile contents:nil attributes:nil];
}
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath: tempFile];
[handle writeData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[handle writeData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[handle writeData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//This will use very little memory as it writes the new file out to disk.
[handle writeData:[NSData dataWithContentsOfMappedFile:pathToHugeFileToPost]];
[handle writeData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[handle synchronizeFile];
[handle closeFile];
//assign body to another memory mapped file
NSData * postBody = [NSData dataWithContentsOfMappedFile:tempFile];
[request setHTTPBody:postBody];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString * returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@",returnString);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment