iOS利用AFNetworking(AFN) 實現圖片上傳

1.上傳圖片以二進制流的形式上傳php

 1 #pragma mark - 文件上傳html

 2 - (IBAction)uploadImagejson

 3 {api

 4     /*服務器

 5      此段代碼若是須要修改,能夠調整的位置網絡

 6      app

 7      1. 把upload.php改爲網站開發人員告知的地址post

 8      2. 把file改爲網站開發人員告知的字段名網站

 9      */ui

10     // 1. httpClient->url

11     

12     // 2. 上傳請求POST

13     NSURLRequest *request = [_httpClient multipartFormRequestWithMethod:@"POST" path:@"upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

14         // 在此位置生成一個要上傳的數據體

15         // form對應的是html文件中的表單

16         

17         

18         UIImage *image = [UIImage imageNamed:@"頭像1"];

19         NSData *data = UIImagePNGRepresentation(image);

20         

21         // 在網絡開發中,上傳文件時,是文件不容許被覆蓋,文件重名

22         // 要解決此問題,

23         // 能夠在上傳時使用當前的系統事件做爲文件名

24         NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

25         // 設置時間格式

26         formatter.dateFormat = @"yyyyMMddHHmmss";

27         NSString *str = [formatter stringFromDate:[NSDate date]];

28         NSString *fileName = [NSString stringWithFormat:@"%@.png", str];

29         

30         

31         /*

32          此方法參數

33          1. 要上傳的[二進制數據]

34          2. 對應網站上[upload.php中]處理文件的[字段"file"]

35          3. 要保存在服務器上的[文件名]

36          4. 上傳文件的[mimeType]

37          */

38         [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];

39     }];//file改成後臺接收的字段或參數

40     

41     // 3. operation包裝的urlconnetion

42     AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];

43     

44     [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

45         NSLog(@"上傳完成");

46     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

47         NSLog(@"上傳失敗->%@", error);

48     }];

49     

50     //執行

51     [_httpClient.operationQueue addOperation:op];

 

當要上傳多張圖片時只需在multipartFormRequestWithMethod方法上添加這些代碼就好

AFNetWorking使用multipartFormRequestWithMethod方法上傳多張圖片問題

int i=0;

NSMutableURLRequest *request = [[AFNetWorkSingleton shareInstance] multipartFormRequestWithMethod:@"POST" path:@"Mindex/getimg" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>formData){

    for(UIImage *eachImage in array)

    {

        NSData *imageData = UIImageJPEGRepresentation(eachImage,0.5);

        [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"file%d",i ] fileName:[NSString stringWithFormat:@"abc%d.jpg",i ] mimeType:@"image/jpeg"];//file改成後臺接收的字段或參數

        i++;

    }

}];

 

2.上傳圖片以二進制流的字符串的形式上傳

-(void)postPhotosToShare_API23_withPid:(NSString *)_pid andUid:(NSString *)_uid andScore:(float)_score andContent:(NSString *)_content andAnonymous:(NSString *)_anonymous andImgArray:(NSMutableArray *)_imgArray

{

path = @"interface/product.php/product/";//path爲網站開發人員告知的除去IP後的地址

    NSURL *baseUrl1 = [NSURL URLWithString:urlIP];//urlIP爲網站開發人員告知的IP地址,例:http://192..168.1.1

    httpClient = [[AFHTTPClient alloc]initWithBaseURL:baseUrl1];

    NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];

    [parameters setObject:_pid forKey:@"pid"];

    [parameters setObject:_uid forKey:@"uid"];

    [parameters setObject:[NSString stringWithFormat:@"%f",_score] forKey:@"score"];

    [parameters setObject:_content forKey:@"content"];

    [parameters setObject:_anonymous forKey:@"anonymous"];

    if (_imgArray.count!=0)

    {

        int imgCount=0;

        for (UIImage *myImg in _imgArray)

        {

            NSData *imageData = UIImageJPEGRepresentation(myImg,0.7);//進行圖片壓縮

            NSString *_encodedImageStr = [imageData base64Encoding];//進行64位轉碼轉爲字符串

            [parameters setObject:_encodedImageStr forKey:[NSString stringWithFormat:@"img[%i]",imgCount]];//進行img[%i]改成後臺接收的字段或參數

            imgCount ++;

        }

    }

    request = [httpClient requestWithMethod:@"POST" path:path parameters:parameters];

    [request setTimeoutInterval:kDataExpiryTime];//設置請求時間

    [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];

    AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc]initWithRequest:request];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];

        [self getResultSuccess:json withTage:Get_API_Tag_23];//對api進行標記,可要可不要

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        [self getResultFailed:error];

    }];

    [operation start];

相關文章
相關標籤/搜索