您好,登錄后才能下訂單哦!
項目需要使用HTTP協議中的POST方法上傳文件,稍微總結了一下,將過程貼出來,方便以后參考。有兩種方法,第一是使用NSMutableURLRequest完全從零開始設置,可以加深對HTTP協議的理解;第二種是直接使用別人封裝好的代碼,如AFNetworking。
NSURL *url = [NSURL URLWithString:@"http://yo.diveinedu.com/upload.php"];NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];request.HTTPMethod = @"POST";//0. 設置分隔符NSString *boundary = @"a1b2c3d4e5f6";[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];NSLog(@"%@", request.allHTTPHeaderFields);NSMutableData *httpBody = [NSMutableData data];//1. 開始的分隔符[httpBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];//2. 設置內容: 標簽名,文件名等[httpBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"fileToUpload\"; filename=\"%@\"\r\n", @"mask0.png"] dataUsingEncoding:NSUTF8StringEncoding]];NSString *path = [[NSBundle mainBundle] pathForResource:@"mask0" ofType:@"png"];NSLog(@"%@", [self typeForPath:path]);//3. 設置內容格式[httpBody appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", [self typeForPath:path]] dataUsingEncoding:NSUTF8StringEncoding]];NSString *body = [[NSString alloc] initWithData:httpBody encoding:NSUTF8StringEncoding];NSLog(@"%@", body);//4. 添加真正的內容NSData *data = [NSData dataWithContentsOfFile:path];[httpBody appendData:data];//5. 添加結束邊界[httpBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];//6. 設置http bodyrequest.HTTPBody = httpBody;//7. 發送請求[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", str);}];
重點:
注意協議中需要使用回車換行(\r\n)的位置,HTTP是一個基于文本行的協議,通過回車換行來控制格式。
注意分隔符(Boundary)的設置,尤其是(--)的增加。
設置后的內容應該是下面的樣子(為了看得更清楚,將回車換行用文字表示出來了):
POST /upload.php HTTP/1.1\r\nHost: yo.diveinedu.com\r\nContent-Type: multipart/form-data; boundary=abcdefghigk\r\n\r\nContent-Disposition: form-data; name="fileToUpload"; filename="mask0.png"\r\nContent-Type: p_w_picpath/png\r\n\r\n--abcdefghigk\r\n圖片數據\r\n--abcdefghigk--\r\n
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];manager.responseSerializer = [AFHTTPResponseSerializer serializer];[manager POST:@"http://yo.diveinedu.com/upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { //1. 方法一// NSError *error;// if (![formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:@"fileToUpload" fileName:[path lastPathComponent] mimeType:@"p_w_picpath/png" error:&error]) {// NSLog(@"error appending part: %@", error);// } //2. 方法二 NSData *data = [NSData dataWithContentsOfFile:path]; [formData appendPartWithFileData:data name:@"fileToUpload" fileName:[path lastPathComponent] mimeType:@"p_w_picpath/png"];} success:^(AFHTTPRequestOperation *operation, id responseObject) { NSData *data = (NSData *)responseObject; NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", str);} failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"%@", error);}];
進行網絡編程的時候,可以使用Wireshark之類的抓包工具輔助調試。可以很明確的看到發送或接收的數據是否正確。
最后祝大家兒童節快樂~~~
http://io.diveinedu.com
http://www.diveinedu.com
http://bbs.diveinedu.com
https://github.com/DiveinEdu-CN
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。