標籤:
iOS開發網路篇—檔案的上傳
說明:檔案上傳使用的時POST請求,通常把要上傳的資料儲存在請求體中。本文介紹如何不藉助第三方架構實現iOS開發中得檔案上傳。
由於過程較為複雜,因此本文只貼出部分關鍵代碼。
主控制器的關鍵代碼:
YYViewController.m
#import "YYViewController.h"#define YYEncode(str) [str dataUsingEncoding:NSUTF8StringEncoding]@interface YYViewController ()@end@implementation YYViewController- (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib.}- (void)upload:(NSString *)name filename:(NSString *)filename mimeType:(NSString *)mimeType data:(NSData *)data parmas:(NSDictionary *)params{ // 檔案上傳 NSURL *url = [NSURL URLWithString:@"http://192.168.1.200:8080/YYServer/upload"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.HTTPMethod = @"POST"; // 佈建要求體 NSMutableData *body = [NSMutableData data]; /***************檔案參數***************/ // 參數開始的標誌 [body appendData:YYEncode(@"--YY\r\n")]; // name : 指定參數名(必須跟伺服器端保持一致) // filename : 檔案名稱 NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", name, filename]; [body appendData:YYEncode(disposition)]; NSString *type = [NSString stringWithFormat:@"Content-Type: %@\r\n", mimeType]; [body appendData:YYEncode(type)]; [body appendData:YYEncode(@"\r\n")]; [body appendData:data]; [body appendData:YYEncode(@"\r\n")]; /***************普通參數***************/ [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { // 參數開始的標誌 [body appendData:YYEncode(@"--YY\r\n")]; NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n", key]; [body appendData:YYEncode(disposition)]; [body appendData:YYEncode(@"\r\n")]; [body appendData:YYEncode(obj)]; [body appendData:YYEncode(@"\r\n")]; }]; /***************參數結束***************/ // YY--\r\n [body appendData:YYEncode(@"--YY--\r\n")]; request.HTTPBody = body; // 佈建要求頭 // 請求體的長度 [request setValue:[NSString stringWithFormat:@"%zd", body.length] forHTTPHeaderField:@"Content-Length"]; // 聲明這個POST請求是個檔案上傳 [request setValue:@"multipart/form-data; boundary=YY" forHTTPHeaderField:@"Content-Type"]; // 發送請求 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { if (data) { NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; NSLog(@"%@", dict); } else { NSLog(@"上傳失敗"); } }];}- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ // Socket 實現斷點上傳 //apache-tomcat-6.0.41/conf/web.xml 尋找 檔案的 mimeType// UIImage *image = [UIImage imageNamed:@"test"];// NSData *filedata = UIImagePNGRepresentation(image);// [self upload:@"file" filename:@"test.png" mimeType:@"image/png" data:filedata parmas:@{@"username" : @"123"}]; // 給本地檔案發送一個請求 NSURL *fileurl = [[NSBundle mainBundle] URLForResource:@"itcast.txt" withExtension:nil]; NSURLRequest *request = [NSURLRequest requestWithURL:fileurl]; NSURLResponse *repsonse = nil; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&repsonse error:nil]; // 得到mimeType NSLog(@"%@", repsonse.MIMEType); [self upload:@"file" filename:@"itcast.txt" mimeType:repsonse.MIMEType data:data parmas:@{ @"username" : @"999", @"type" : @"XML"}];}@end
補充說明:
檔案上傳請求資料格式
部分檔案的MIMEType
iOS開發網路篇—檔案的上傳