代码下载地址:上传图片到网站代码
在论坛有些人问到怎样把一张图片上传到网站。其实很简单。下面我和大家分享一下。
有两个方法两解决这个问题。一个是使用BASE64来编码文件然后插入到XML或者JSON的文件中然后上传, 另外一个就是模拟一个HTML的提交方式上传。这篇教程使用HTML提交方式。
大家可以下载代码边看边学习。
下载代码后打开testPickerViewController.h 我们需要加入一个上传的UIBUTTON.
IBOutlet UIButton *upload;
和一个上传的方法 - (IBAction)uploadImage;
打开interface builder然后把这个按钮连接起来。请参考代码
主要的uploadImage函数如下: - (IBAction)uploadImage {/* turning the image into a NSData object getting the image back out of the UIImageView setting the quality to 90 */ NSData *imageData = UIImageJPEGRepresentation(image.image, 90); // setting up the URL to post to NSString *urlString = @"/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:@"rn--%@rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name="userfile"; filename="ipodfile.jpg"rn"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-streamrnrn"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[NSData dataWithData:imageData]]; [body appendData:[[NSString stringWithFormat:@"rn--%@--rn",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];
NSLog(returnString); }
这样编译代码以后你就可以选择图片上传了。
但是这样还不能结束。留意到上面的代码 NSString *urlString = @"/test-upload.php";这个是要上传到的网址,你如果有自己的服务器的话,还必须要上传一个PHP的文件用来接收上传的图片。 这个PHP的代码其实也不复杂。代码如下:
$uploaddir = './uploads/'; $file = basename($_FILES['userfile']['name']); $uploadfile = $uploaddir . $file;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {echo "/uploads/{$file}"; }
代码很简单,懂PHP的朋友可以自己去修改。