-(NSMutableURLRequest *)requestWithURL:(NSURL *)url withBody:(NSMutableDictionary *)body withUrlAndAttachedFile:(NSString *)fileAndUrl withFileName:(NSString *)fileName withFileFormat:(NSString *)fileFormat
{
NSMutableURLRequest *request;
NSString *requestBody;
request = [[NSMutableURLRequest alloc] initWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:60];
request= [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file_0\"; filename=\"%@.%@\"\r\n", fileName, fileFormat] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
NSData *postData = [[NSData alloc] initWithContentsOfURL:[NSURL fileURLWithPath:fileAndUrl]];
[postbody appendData:[NSData dataWithData:postData]];
[postbody appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// iterate body dict
NSEnumerator *enumerator = [body keyEnumerator];
id key;
// extra parens to suppress warning about using = instead of ==
while((key = [enumerator nextObject])){
//NSLog(@"key=%@ value=%@", key, [body objectForKey:key]);
[postbody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[body objectForKey:key] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
// close form
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
return request;
}
references:
http://stackoverflow.com/questions/4458112/mac-os-nsurlconnection-in-iteration
No comments:
Post a Comment