Home News Forum Social Networking Support Us Advertise

Spanish Lesson 1 ($1.99)

aWake!Gently ($1.99)

The Bird & The Snail - Knock Knock - Deluxe ($4.99)

Match-It Trains ($0.99)

Tangled ($0.99)

iFlatter ($0.99)

The 15 puzzle ($0.99)

Tap Forms Database ($8.99)

Higher or Lower Card Game (Hi Lo) ($0.99)

Red Pixel ($0.99)

Time-Shift Radio ($0.99)

Want your application advertised here? Only $10/week!

Go Back   iPhone Dev SDK Forum > iPhone SDK Development Forums > iPhone SDK Development

Reply
 
LinkBack Thread Tools Display Modes
Old 08-27-2008, 04:56 PM   #1 (permalink)
Senior Member
 
Join Date: Apr 2008
Posts: 156
Rep Power: 0
uprise78 is an unknown quantity at this point
Default Posting a File to Web Site

I have an audio file that was recorded on the iPhone and I would like to POST it to a website for further processing/storage. How would this be done using Obj-C? If it were .NET or PHP or Python I would just base64 encode the file, upload, and base64 decode server-side. I can't seem to be able to successfully send a file over the wire. Any ideas?
uprise78 is offline   Reply With Quote
Old 08-28-2008, 04:35 PM   #2 (permalink)
Lost in a sea of code
iPhone Dev SDK Supporter
 
BostonMerlin's Avatar
 
Join Date: Apr 2008
Location: Boston
Posts: 368
Rep Power: 0
BostonMerlin is an unknown quantity at this point
Default

I have to do the same thing only with images. i'm running an asp.net app on the server side which needs to accept a posted image from the iphone.

anyone have a direction on this?

Thanks
John
__________________
----------------------------------------------------------------------
I love being a dad, flying airplanes and writing code.
----------------------------------------------------------------------
Follow me on Twitter: @BostonMerlin
----------------------------------------------------------------------
iPhone Apps: The Pilots Library
BostonMerlin is offline   Reply With Quote
Old 08-28-2008, 04:44 PM   #3 (permalink)
Member
 
Join Date: Jul 2008
Posts: 75
Rep Power: 1
hijinks is on a distinguished road
Default

I am finishing up a tutorial on this. I hope to have it done by tomorrow.. It will focus on images but should work for any file
__________________
Iphone Noob iPhone Development Blog. Learn to develop for the iPhone SDK with me
hijinks is offline   Reply With Quote
Old 08-28-2008, 04:55 PM   #4 (permalink)
Senior Member
 
Join Date: Apr 2008
Posts: 156
Rep Power: 0
uprise78 is an unknown quantity at this point
Default

Just figured it out. Base64 encode using external library, upload, decode. Done.
uprise78 is offline   Reply With Quote
Old 08-28-2008, 11:33 PM   #5 (permalink)
pdm
Member
 
Join Date: Aug 2008
Posts: 56
Rep Power: 1
pdm is on a distinguished road
Default

Hi guys,
I'm also working on the same scenario, i,e posting audio/video/image file to the web server.
Could anyone please provide some hint regarding the same.
Sample application code will definetly help.
Could you please help me in this regard.

Thanks in advance.

-pdm
pdm is offline   Reply With Quote
Old 08-29-2008, 01:44 AM   #6 (permalink)
zig to the zag
 
Join Date: Jul 2008
Posts: 45
Rep Power: 0
zig_zag_love is on a distinguished road
Default

I would love a code sample for this as well
zig_zag_love is offline   Reply With Quote
Old 08-29-2008, 06:57 AM   #7 (permalink)
Member
 
Join Date: Jul 2008
Posts: 75
Rep Power: 1
hijinks is on a distinguished road
Default

I am pretty sure you can do it without base64 encoding. I am going to be using NSData and then just putting the whole post into a NSString and sending that just like you would see if you sniffed the line to see the transaction.. I will post updates on my failure or success

But really if you say you want something.. please show code and contribute and not just say you did it.
__________________
Iphone Noob iPhone Development Blog. Learn to develop for the iPhone SDK with me
hijinks is offline   Reply With Quote
Old 08-29-2008, 07:54 AM   #8 (permalink)
Senior Member
iPhone Dev SDK Supporter
 
Join Date: Aug 2008
Posts: 225
Rep Power: 0
bikr is an unknown quantity at this point
Default

I think hijinks meant: If you say you did something, not want.. But I agree with him 100% Share man Share!!
bikr is offline   Reply With Quote
Old 08-29-2008, 09:52 AM   #9 (permalink)
Member
 
Join Date: Jul 2008
Posts: 75
Rep Power: 1
hijinks is on a distinguished road
Default

yep guys I got it working. It only took me 2 hours of comparing a normal html post with the one from my app in wireshark but I got it working

I will post a solution on my blog in a little bit
__________________
Iphone Noob iPhone Development Blog. Learn to develop for the iPhone SDK with me
hijinks is offline   Reply With Quote
Old 08-29-2008, 10:18 AM   #10 (permalink)
Senior Member
 
Join Date: Apr 2008
Posts: 156
Rep Power: 0
uprise78 is an unknown quantity at this point
Default

Client side code. Message was base64 encoded before being sent to this function.

Code:
- (void)sendSerializedGreeting:(NSString *)message
{
	// Show a loading indicator
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	NSString *greetingURL = [NSString stringWithFormat:@"http://yourwebsite.com", [[UIDevice currentDevice] uniqueIdentifier]];
	NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:greetingURL]
															  cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	NSDictionary *headerFieldsDict = [NSDictionary dictionaryWithObjectsAndKeys:@"text/xml; charset=utf-8", @"Content-Type", nil];
	
	[theRequest setHTTPBody:[message dataUsingEncoding:NSUTF8StringEncoding]];
	[theRequest setAllHTTPHeaderFields:headerFieldsDict];
	[theRequest setHTTPMethod:@"POST"];
	
	// create the connection with the request and start loading the data
	NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
	
	if (theConnection == nil)
	{
		NSLog(@"Failed to create the connection");
	}
}
Server side code:
// PHP
Code:
$file = base64_decode(file_get_contents("php://input"));
// ASP
Code:
StreamReader sr = new StreamReader(Page.Request.InputStream);
string file = Encoding.ASCII.GetString(Convert.FromBase64String(sr.ReadToEnd()));
uprise78 is offline   Reply With Quote
Old 08-29-2008, 10:30 AM   #11 (permalink)
Member
 
Join Date: Jul 2008
Posts: 75
Rep Power: 1
hijinks is on a distinguished road
Default

Here is a blog post about it

Post a UIImage to the web | Iphone Noob

Here is the meat of the code to post

Code:
NSData *imageData = UIImageJPEGRepresentation(image.image, 90);
	// setting up the URL to post to
	NSString *urlString = @"http://iphone.zcentric.com/test-upload.php";
	
	// setting up the request object now
	NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
	[request setURL:[NSURL URLWithString:urlString]];
	[request setHTTPMethod:@"POST"];
	
	/*
	 add some header info now
	 we always need a boundary when we post a file
	 also we need to set the content type
	 
	 You might want to generate a random boundary.. this is just the same 
	 as my output from wireshark on a valid html post
	*/
	NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
	NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
	[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
	
	/*
	 now lets create the body of the post
	*/
	NSMutableData *body = [NSMutableData data];
	[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];	
	[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.jpg\"\r\n"] 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]];
	// setting the body of the post to the reqeust
	[request setHTTPBody:body];
	
	// now lets make the connection to the web
	NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
	NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
__________________
Iphone Noob iPhone Development Blog. Learn to develop for the iPhone SDK with me
hijinks is offline   Reply With Quote
Old 08-29-2008, 10:31 AM   #12 (permalink)
Member
 
Join Date: Jul 2008
Posts: 75
Rep Power: 1
hijinks is on a distinguished road
Default

hey thanks uprise78

now we have two good options to uploading files.. base64 and the html post way
__________________
Iphone Noob iPhone Development Blog. Learn to develop for the iPhone SDK with me
hijinks is offline   Reply With Quote
Old 08-29-2008, 10:54 AM   #13 (permalink)
Senior Member
 
Join Date: Apr 2008
Posts: 156
Rep Power: 0
uprise78 is an unknown quantity at this point
Default

hijinks,

Your code looks good too. The only think I would suggest is modifying the uploadImage method to be like this:
Code:
- (IBAction)uploadImage {
    [NSThread detachNewThreadSelector:@selector(doUploadOfImage) toTarget:self withObject:nil];
}

- (void)doUploadOfImage
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    ... ALL OF THE ORIGINAL CODE THAT WAS IN - (IBAction)uploadImage ...

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [pool release];
}
This will keep the UI from freezing if the upload is slow and it will get the little spinner going.

Nicely done!
uprise78 is offline   Reply With Quote
Old 08-29-2008, 09:15 PM   #14 (permalink)
Lost in a sea of code
iPhone Dev SDK Supporter
 
BostonMerlin's Avatar
 
Join Date: Apr 2008
Location: Boston
Posts: 368
Rep Power: 0
BostonMerlin is an unknown quantity at this point
Default

It appears i have the client side code working so my phone is posting an image off to my server running a small asp.net 2.0 webform. I'm using iphone noobs example from his tutorial here (Post a UIImage to the web | Iphone Noob).

My .net webform is setup to receive the file but is not working. i've tried different techniques to get at the file coming into the stream but none work. I'm positive it's because i dont understand the image format being pushed from the phone to the server and how to decode that format on my server.

on my server i have just a few lines of code to accept that stream...

Code:
Dim imageConverter As New System.Drawing.ImageConverter
Dim image As Image = imageConverter.ConvertFrom(Page.Request.InputStream)
image.Save("c:\images\test.png")
the response being returned back from my server to the phone is 'imageconverter cannot convert from system.web.httpinputstream.

Thoughts from those .NET gurus in the crowd?

thanks
john
__________________
----------------------------------------------------------------------
I love being a dad, flying airplanes and writing code.
----------------------------------------------------------------------
Follow me on Twitter: @BostonMerlin
----------------------------------------------------------------------
iPhone Apps: The Pilots Library
BostonMerlin is offline   Reply With Quote
Old 08-29-2008, 10:24 PM   #15 (permalink)
Lost in a sea of code
iPhone Dev SDK Supporter
 
BostonMerlin's Avatar
 
Join Date: Apr 2008
Location: Boston
Posts: 368
Rep Power: 0
BostonMerlin is an unknown quantity at this point
Default

Uprise, what did you use to base64 encode?

thanks
john



Quote:
Originally Posted by uprise78 View Post
Client side code. Message was base64 encoded before being

sent to this function.

Code:
- (void)sendSerializedGreeting:(NSString *)message
{
	// Show a loading indicator
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	NSString *greetingURL = [NSString stringWithFormat:@"http://yourwebsite.com", [[UIDevice currentDevice] uniqueIdentifier]];
	NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:greetingURL]
															  cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	NSDictionary *headerFieldsDict = [NSDictionary dictionaryWithObjectsAndKeys:@"text/xml; charset=utf-8", @"Content-Type", nil];
	
	[theRequest setHTTPBody:[message dataUsingEncoding:NSUTF8StringEncoding]];
	[theRequest setAllHTTPHeaderFields:headerFieldsDict];
	[theRequest setHTTPMethod:@"POST"];
	
	// create the connection with the request and start loading the data
	NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
	
	if (theConnection == nil)
	{
		NSLog(@"Failed to create the connection");
	}
}
Server side code:
// PHP
Code:
$file = base64_decode(file_get_contents("php://input"));
// ASP
Code:
StreamReader sr = new StreamReader(Page.Request.InputStream);
string file = Encoding.ASCII.GetString(Convert.FromBase64String(sr.ReadToEnd()));
__________________
----------------------------------------------------------------------
I love being a dad, flying airplanes and writing code.
----------------------------------------------------------------------
Follow me on Twitter: @BostonMerlin
----------------------------------------------------------------------
iPhone Apps: The Pilots Library
BostonMerlin is offline   Reply With Quote
Old 08-29-2008, 11:10 PM   #16 (permalink)
Lost in a sea of code
iPhone Dev SDK Supporter
 
BostonMerlin's Avatar
 
Join Date: Apr 2008
Location: Boston
Posts: 368
Rep Power: 0
BostonMerlin is an unknown quantity at this point
Default

got it. using iphone noobs example i had to remove several lines of code from his body string to get this to work. looking at noobs code.. make the following changes:

Code:
NSMutableData *body = [NSMutableData data];
	//[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
	//[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.jpg\"\r\n"] 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]];
	// setting the body of the post to the reqeust
	[request setHTTPBody:body];
on the server side (for those of you who might be using asp.net).. all that's needed is:

Code:
Dim sr as New StreamReader(Page.Request.InputStream)
Page.Reqeust.SaveAs("c:\my.png", False)

This was one of the last big hurdles for my app.. which i've had many such hurdles. I'm now utilizing threads, webservices to .net servers both pushing data back and forth, posting images to the server and retrieving images from the server. Save those images on the phone, working with myssql, dynamically upating webviews with content and images, tracking javascript events in those views etc. The list seems to go on and on. I do things like this frequently at my day job as a windows dev.. but I'm finally getting my head wrapped around mac development.. and it feels good!

Thanks again for everyones help.
John
__________________
----------------------------------------------------------------------
I love being a dad, flying airplanes and writing code.
----------------------------------------------------------------------
Follow me on Twitter: @BostonMerlin
----------------------------------------------------------------------
iPhone Apps: The Pilots Library
BostonMerlin is offline   Reply With Quote
Old 09-15-2008, 10:12 AM   #17 (permalink)
Member
 
Join Date: Sep 2008
Posts: 60
Rep Power: 1
gagandeepb is on a distinguished road
Default

Hi,

I am using the same thing to upload the xml but doesn't seems to be work. My webform Default.aspx is running there on IIS server and i put these two lines in Page_Load. I am using uprise way http post and set request body.

Dim sr as New StreamReader(Page.Request.InputStream)
Page.Reqeust.SaveAs("c:\my.xml", False)

Can any body help how to use this sr object
gagandeepb is offline   Reply With Quote
Old 09-15-2008, 10:19 AM   #18 (permalink)
Lost in a sea of code
iPhone Dev SDK Supporter
 
BostonMerlin's Avatar
 
Join Date: Apr 2008
Location: Boston
Posts: 368
Rep Power: 0
BostonMerlin is an unknown quantity at this point
Default

if all you're doing is posting xml you dont need stream reader on the .net side of things. simply "POST" the xml from the client to the server (default.aspx) and receive the post on the server via (request.form("myXmlString")). Once you have the xml on the server just save it to a file.

hope that helps
john
__________________
----------------------------------------------------------------------
I love being a dad, flying airplanes and writing code.
----------------------------------------------------------------------
Follow me on Twitter: @BostonMerlin
----------------------------------------------------------------------
iPhone Apps: The Pilots Library
BostonMerlin is offline   Reply With Quote
Old 09-19-2008, 02:14 AM   #19 (permalink)
Member
 
Join Date: Sep 2008
Posts: 60
Rep Power: 1
gagandeepb is on a distinguished road
Default

Thanks john for reply

i try with request.form("myXmlString") but it always return error in response. When i used this with simple text then it works, seems not able to parse <> tags.
Anyway i used XMLDoc to receive the Request.Inputstream and then doc.Save(""); to save it locally. That's i wanted to send the xml at server side.
gagandeepb is offline   Reply With Quote
Old 11-04-2008, 12:25 PM   #20 (permalink)
Member
 
roberthuttinger's Avatar
 
Join Date: Sep 2008
Posts: 74
Rep Power: 1
roberthuttinger is on a distinguished road
Default

so can I use the code to POST data? can I use this method to load a page that inserts POST data into a MySQL db? Id like to send an NSString to my server and enter it into a db. Trying this method I cannot get it to work..Any tutorials out there?
cheers.bo
roberthuttinger is offline   Reply With Quote
Old 12-15-2008, 02:01 PM   #21 (permalink)
Junior Member
 
Join Date: Dec 2008
Posts: 1
Rep Power: 0
dcanatsey is on a distinguished road
Default Base64 encoding library?

What external library did you use and how did you implement it in XCode?

Quote:
Originally Posted by uprise78 View Post
Just figured it out. Base64 encode using external library, upload, decode. Done.
Thanks in advance.
dcanatsey is offline   Reply With Quote
Old 01-13-2009, 01:02 PM   #22 (permalink)
Junior Member
 
Pedro Valentini's Avatar
 
Join Date: Oct 2008
Location: Rio de Janeiro, Brazil
Posts: 20
Rep Power: 0
Pedro Valentini is on a distinguished road
Default

Good work.
Its work fine with php, but in RubyOnRails server I'm get the error:
Code:
  Status: 500 Internal Server Error
  bad content body
I'm looking for some solution and will post here when found.
Thank you
Pedro Valentini is offline   Reply With Quote
Old 02-24-2009, 01:56 AM   #23 (permalink)
Junior Member
 
Join Date: Nov 2008
Posts: 4
Rep Power: 0
demowolf is on a distinguished road
Default

Quote:
Originally Posted by hijinks View Post
Here is a blog post about it

Post a UIImage to the web | Iphone Noob

Here is the meat of the code to post

Code:
NSData *imageData = UIImageJPEGRepresentation(image.image, 90);
	// setting up the URL to post to
	NSString *urlString = @"http://iphone.zcentric.com/test-upload.php";
	
	// setting up the request object now
	NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
	[request setURL:[NSURL URLWithString:urlString]];
	[request setHTTPMethod:@"POST"];
	
	/*
	 add some header info now
	 we always need a boundary when we post a file
	 also we need to set the content type
	 
	 You might want to generate a random boundary.. this is just the same 
	 as my output from wireshark on a valid html post
	*/
	NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
	NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
	[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
	
	/*
	 now lets create the body of the post
	*/
	NSMutableData *body = [NSMutableData data];
	[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];	
	[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.jpg\"\r\n"] 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]];
	// setting the body of the post to the reqeust
	[request setHTTPBody:body];
	
	// now lets make the connection to the web
	NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
	NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
I was courious why everybody stop talking about upload audio files , and talk about posting Images ?

I think it is easy and reliable to upload image through HTTP POST request .
But it's hard to upload big files, such as audio files, mp4 files. Can we do this still through HTTP POST ? I guess not so.

Even we can do this, is there some progress bar to know how much of this file has been transferred ?
demowolf is offline   Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


» Advertisements


» Stats
Members: 8,229
Threads: 20,197
Posts: 90,213
Top Poster: RickMaddy (2,121)
Welcome to our newest member, jrsiqueira
Powered by vBadvanced CMPS v3.1.0

All times are GMT -5. The time now is 02:06 PM.
Powered by vBulletin® Version 3.8.0
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.2.0