本文内容来自于王志刚 《软件创富密码:iPhone应用程序开发攻略之深刻浅出Objective-C 2.0》一书,修改了部份内容。php
截图以下:html
Download:api
代码以下:服务器
// // AppController.h // File Upload Download // // Created by longx-app on 13-9-15. // Copyright (c) 2013年 longx-app. All rights reserved. // #import <Foundation/Foundation.h> @interface AppController : NSObject <NSURLConnectionDataDelegate> { NSMutableData *m_data; // 图片数据 BOOL m_is_upload; // 上传标志 NSString *action_type; // 操做类型 NSMutableData *m_result; // 返回数据 } @property (strong, nonatomic) IBOutlet UIImageView *imageView; - (IBAction)upload:(id)sender; - (IBAction)download:(id)sender; @end
// // AppController.m // File Upload Download // // Created by longx-app on 13-9-15. // Copyright (c) 2013年 longx-app. All rights reserved. // #import "AppController.h" @implementation AppController @synthesize imageView=_imageView; - (id)init { if (self = [super init]) { // equivalent to "self does not equal nil" m_is_upload = TRUE; } return self; } - (IBAction)upload:(id)sender { action_type = @"UPLOAD"; if (m_data == nil) { return; } // 上传的状况下 if (m_is_upload) { m_is_upload = FALSE; //m_data = [[NSMutableData data] retain]; m_result = [[NSMutableData data] retain]; NSData *pData = UIImagePNGRepresentation([_imageView image]); [self uploadPictureProcess:pData]; return; } return; } - (IBAction)download:(id)sender { action_type = @"DOWNLOAD"; m_data = [[NSMutableData data] retain]; // 请求 NSString *url = @"http://coolapp-image.stor.sinaapp.com/orginal.png"; NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]; NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:req delegate:self]; if (con == NULL) { return; } } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { if ([action_type isEqualToString:@"DOWNLOAD"]) { // 追加接收的数据 [m_data appendData:data]; } else if ([action_type isEqualToString:@"UPLOAD"]) { // 追加数据 [m_result appendData:data]; } } // 结束网络链接 - (void)connectionDidFinishLoading:(NSURLConnection *)connection { if ([action_type isEqualToString:@"DOWNLOAD"]) { UIImage *img = [[UIImage alloc] initWithData:m_data]; [_imageView setImage:img]; } else if ([action_type isEqualToString:@"UPLOAD"]) { NSLog(@"Upload finish!!"); m_is_upload = TRUE; // 打印结果 NSMutableString *result = [[NSMutableString alloc] initWithData:m_result encoding:NSUTF8StringEncoding]; NSLog(@"%@", [NSString stringWithString:result]); m_result = nil; } } // 上传图片 - (void)uploadPictureProcess:(NSData*)imgData { //UIApplication *app = [UIApplication sharedApplication]; // 初始化 // 链接设置,建立request对象 NSString *url = @"http://1.coolapp.sinaapp.com/uploadpicture.php"; NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]; // 进行HTTP头设置,首先设置主机,接着设置用户代理、语言和文字编码等。中文环境下必须GB2312或者UTF-8 [req addValue:[NSString stringWithFormat:@"1.coolapp.sinaapp.com"] forHTTPHeaderField:@"Host"]; [req addValue:[NSString stringWithFormat:@"Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3 like Mac OS X; zh-Hans)"] forHTTPHeaderField:@"User-Agent"]; [req addValue:[NSString stringWithFormat:@"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"] forHTTPHeaderField:@"Accept"]; [req addValue:[NSString stringWithFormat:@"zh,en-us;q=0.7,en;q=0.3"] forHTTPHeaderField:@"Accept-Language"]; [req addValue:[NSString stringWithFormat:@"gzip,deflate"] forHTTPHeaderField:@"Accept-Encoding"]; [req addValue:[NSString stringWithFormat:@"gb2312,utf-8;q=0.7,*;q=0.7"] forHTTPHeaderField:@"Accept-Charset"]; [req addValue:[NSString stringWithFormat:@"300"] forHTTPHeaderField:@"Keep-Alive"]; [req addValue:[NSString stringWithFormat:@"keep-alive"] forHTTPHeaderField:@"Connection"]; [req addValue:[NSString stringWithFormat:@"max-age=0"] forHTTPHeaderField:@"Cache-Control"]; // 将HTTP方法设置POST [req setHTTPMethod:@"POST"]; // 设置内容类型,注意必须是“multipart/form-data; boundary=XX”与form表单中上传文件的设置同样。 NSString *boundary = [NSString stringWithFormat:@"---------------------------12345678912345678912345678912"]; NSString *content_type = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; [req addValue:content_type forHTTPHeaderField:@"Content-Type"]; // 主体(Body) NSMutableData *body = [[NSMutableData data] retain]; // 注意中文环境中必须使用NSUTF8StringEncoding [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"up\"; filename=\"test.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; //将主体(body)的内容类型设置为“image/png”,若是是JPEG图片则为“image/jpeg”。 [body appendData:[[NSString stringWithFormat:@"Content-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; //追加图片数据 [body appendData:imgData]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [req setHTTPBody:body]; // 服务器链接开始 NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:req delegate:self]; if(con == NULL){ return; } } @end
PHP服务器端代码以下:网络
由于服务器使用新浪云服务器,因此有些api不同:app
<?php // 保存接收图片 // var_dump($_FILES['up']['tmp_name']); if ($_FILES['up']['tmp_name']) { file_put_contents( SAE_TMP_PATH . '/test.png' , file_get_contents($_FILES['up']['tmp_name']) ); $s = new SaeStorage(); $s->upload( 'image' , 'remote_test_file.png' , SAE_TMP_PATH . '/test.png' ); echo "OK"; } else { echo "NG"; } //file_put_contents( SAE_TMP_PATH . '/mycode.txt' , 'dummy test' ); //echo file_get_contents( SAE_TMP_PATH . '/mycode.txt' ); // will echo dummy test; // //$s = new SaeStorage(); //$s->upload( 'resources' , 'remote_file.txt' , SAE_TMP_PATH . '/mycode.txt' ); ?>
完ui