Pages

Thursday 5 May 2011

Upload File to FTP Server on iPhone

Implementing the file upload to FTP Server:



I use a PHP Page to upload the file  and have PHP handle the uploading....
This code is used to upload a photo, but it can be adapted to work with any file.
PHP Code:
<?php
$uploaddir = 'photos/';
$file = basename($_FILES['userfile']['name']);                    //userfile should give in the iphone server upload code
$uploadfile = $uploaddir . $file;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "upload success";
} else {
    echo "error uploading";
}
?>
IPhone Code:
NSData * rfile = [[NSData alloc]initWithContentsOfURL:@"image url / location of your media"];
NSString *urlString = @"http://www.yourdomainName.com/yourPHPPage.phpp";
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]];                                               //userfile should match with your php

[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:rfile]];
[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];
NSLog(@"Response from Server : %@",returnString);


Finally you will get the response as "Upload Success" otherwise show you "Error uploading"
Let me know if you have any queries



 

0 comments:

Post a Comment

Feel Free to Share your Views