I used the below code for uploading a image file.
The connection with server is successfully connected.
But the image was not uploaded.Can anyone tell me the reason?
The connection with server is successfully connected.
But the image was not uploaded.Can anyone tell me the reason?
Code:
- (NSData *)generatePostDataForData:(NSData *)uploadData
{
NSLog(@"generatePostDataForData");
// Generate the post header:
NSString *post = [NSString stringWithCString:"--AaB03x\r\nContent-Disposition: form-data; name=\"upload[file]\"; filename=\"somefile\"\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n\r\n" encoding:NSASCIIStringEncoding];
// Get the post header int ASCII format:
NSData *postHeaderData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Generate the mutable data variable:
NSMutableData *postData = [[NSMutableData alloc] initWithLength:[postHeaderData length] ];
[postData setData:postHeaderData];
// Add the image:
[postData appendData: uploadData];
// Add the closing boundry:
[postData appendData: [@"\r\n--AaB03x--" dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
NSLog(@"postLengthhhhhhhhhhhhhhhhhhh %d bytes of data",[postData length]);
// Return the post data:
return postData;
}
-(IBAction) displayupload:(id) sender
{
// Generate the postdata:
NSLog(@"Display upload");
NSString *path=@"http://commons.wikimedia.org/wiki/File:Chamomile_flowers.jpg";
NSData *mydata = [[NSData alloc] initWithContentsOfFile:path];
NSData *postData = [self generatePostDataForData: mydata];
NSLog(@"Succeeded! Received %d bytes of data",[postData length]);
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSLog(@"postLength=%@",postLength);
// Setup the request:
NSMutableURLRequest *uploadRequest = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://myserver.com/myimages/submit.aspx"] cachePolicy: NSURLRequestReloadIgnoringLocalCacheData timeoutInterval: 30 ] autorelease];
[uploadRequest setHTTPMethod:@"POST"];
[uploadRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
[uploadRequest setValue:@"multipart/form-data; boundary=AaB03x" forHTTPHeaderField:@"Content-Type"];
[uploadRequest setHTTPBody:postData];
// Execute the reqest:
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:uploadRequest delegate:self];
if (conn)
{
NSLog(@"Connection succeeded");
// Connection succeeded (even if a 404 or other non-200 range was returned).
}
else
{
NSLog(@"Connection failed");
// Connection failed (cannot reach server).
}
}