Created
October 18, 2011 23:36
-
-
Save YANOUSHek/1297073 to your computer and use it in GitHub Desktop.
Cocoa uploader for LetsCrate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
NSURL *url = [NSURL URLWithString:@"https://api.letscrate.com/1/files/upload.json"]; | |
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url]; | |
[req setHTTPMethod:@"POST"]; | |
NSString* authString = [[[NSString stringWithFormat:@"%@:%@", @"LOGIN", @"PASSWORD"] dataUsingEncoding:NSUTF8StringEncoding] base64Encoding]; | |
authString = [NSString stringWithFormat: @"Basic %@", authString]; | |
[req setValue:authString forHTTPHeaderField:@"Authorization"]; | |
NSString *boundary = @"0xKhTmLbOuNdArY"; | |
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; | |
[req setValue:contentType forHTTPHeaderField:@"Content-type"]; | |
NSString *imagePath = [NSString stringWithFormat:@"%@/%@", directory, filename]; | |
NSData *imageData = [NSData dataWithContentsOfFile:imagePath options:0 error:nil]; | |
//adding the body: | |
NSMutableData *postBody = [NSMutableData data]; | |
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; | |
[postBody appendData:[@"Content-Disposition: form-data; name=\"crate_id\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; | |
[postBody appendData:[[NSString stringWithFormat:@"%d", crateId] dataUsingEncoding:NSUTF8StringEncoding]]; | |
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; | |
[postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"a.png\"\r\n\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]]; | |
[postBody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; | |
[postBody appendData:imageData]; | |
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; | |
[req setHTTPBody:postBody]; | |
[req setValue:[NSString stringWithFormat:@"%d", [postBody length]] forHTTPHeaderField:@"Content-length"]; | |
[req setTimeoutInterval:5]; | |
NSURLResponse* response = nil; | |
NSError* error = nil; | |
NSData* reply = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment