/ Published in: Objective C
So here is something a lot of people have been wondering to do in the forums. How do I take a UIImage or any image and post it to a website. So this will go over how to do that.
There are two ways to tackle this issue. One we can base64 encode the file and post is normally inside a XML or JSON instance or we can simulate a normal HTML post. This tutorial will go over the HTML post.
There are two ways to tackle this issue. One we can base64 encode the file and post is normally inside a XML or JSON instance or we can simulate a normal HTML post. This tutorial will go over the HTML post.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
- (IBAction)uploadImage { /* turning the image into a NSData object getting the image back out of the UIImageView setting the quality to 90 */ // setting up the URL to post to // setting up the request object now [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 */ [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; /* now lets create the body of the post */ --%@ ",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.jpg\" "] dataUsingEncoding:NSUTF8StringEncoding]]; "] dataUsingEncoding:NSUTF8StringEncoding]]; --%@-- ",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]; NSLog(returnString); } Here is the php function to grab the uploaded file: $uploaddir = './uploads/'; $file = basename($_FILES['userfile']['name']); $uploadfile = $uploaddir . $file; if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { echo "http://iphone.zcentric.com/uploads/{$file}"; }
URL: http://iphone.zcentric.com/?p=218