Thursday, December 23, 2010

Image upload in iphone

Hi
Today I am sharing image browse and image upload tutorial with you..
Call following method for uploading photo you need to pass image data and file name of your image
Other thing you need small php code for uploading..

  







Please make sure your upload directory have read/write permission 
<?php
$uploaddir = 'photos/';
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir . $file;
         if(move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)){
         echo "YES";
         }else{
         echo "NO";
         }
?>


- (NSString *)uploadImageFunction:(NSData *)imageData filename:(NSString *)filename{
   
    // Please Specify your php script Url here
     NSString *urlString = @"http://127.0.0.1/iphone/uploader.php";
   
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
     
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
   
    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n",filename]] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:body];
   
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    return (returnString);
}
you can download zip and php script from here.

No comments:

Post a Comment