App中個人信息頁面,通常都會有設置頭像的功能.當用戶從相冊中選擇圖像或者拍攝照片成功后,一般都需要將照片發送到服務器進行保存,以方便用戶在其他設備或者再次登陸后,能再次從服務器請求到設置的照片.項目中通過AFN,實現起來很方便.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
- ( void )upload{ NSData *imageData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@ "mine.jpeg" ofType:nil]]; NSDictionary* URLParameters = @{ //設置請求頭 }; NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@ "mine.jpeg" ofType:nil]]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSURLResponse *repsonse = nil; [NSURLConnection sendSynchronousRequest:request returningResponse:&repsonse error:nil]; NSString *mimeType = repsonse.MIMEType; NSLog(@ "%@" , repsonse.MIMEType); [[AFHTTPSessionManager manager] POST:@ "上傳網址" parameters:URLParameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { [formData appendPartWithFileData:imageData name:@ "file" fileName:@ "mine.jpeg" mimeType:mimeType]; } progress:^(NSProgress * _Nonnull uploadProgress) { // } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { //處理成功 } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { //處理失敗 }]; } |
mine.jpeg是在項目存在的圖片,編譯時會以NSBundle的形式存在.首先通過NSURLConnection同步發送請求獲取MIMEType.然后使用AFN,可以將需要上傳的imageData通過方法appendPartWithFileData:放在請求體中,然后傳入已經獲得的MIMEType,就能順利實現上傳了.
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.jianshu.com/p/e78b235d0dbc?utm_source=tuicool&utm_medium=referral