[iOS AFNetworking架構實現HTTP請求、多檔案圖片上傳下載]

來源:互聯網
上載者:User

標籤:

簡單的JSON的HTTP傳輸就不說了,看一個簡單的DEMO吧。

主要明白parameters是所填參數,類型是字典型。我把這部分代碼封裝起來了,以便多次調用。也許寫在一起更清楚點。

#pragma mark - JSON方式post提交資料- (void)postJSONWithUrl:(NSString *)urlStr parameters:(id)parameters success:(void (^)(id responseObject))success fail:(void (^)())fail{    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];    // 佈建要求格式    manager.requestSerializer = [AFJSONRequestSerializer serializer];    // 設定返回格式    manager.responseSerializer = [AFHTTPResponseSerializer serializer];    [manager POST:urlStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {        //查看返回資料        //NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];        if (success) {            success(responseObject);        }    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {        NSLog(@"%@", error);        if (fail) {            fail();        }    }];}

下面是調用方式:返回的json會存在id的變數裡,這個jsondataAFN架構有自動轉換成字典型,用健直接可以取到值。

//jason解析,根據上傳id從資料庫取出使用者資訊-(void)jasontest{    //訪問的URL    NSString *url = @"http://localhost:8888/chepaishibie/selectuser.php";    //需要傳進去的參數    NSDictionary *parameter = @{@"Driverid": @"10000"};    //GET或者POST請求    [[ShenAFN sharedInstance] JSONDataWithUrl:url parameter:parameter success:^(id jsondata) {        //返回的字元,並輸出        NSLog(@"success:\n%@", jsondata);        //如果是其他字元,可以用以下語句解析返回的語句        //NSString *result = [[NSString alloc] initWithData:jsondata encoding:NSUTF8StringEncoding];        //如果是json格式,可以通過這種方式擷取變數        id info1=jsondata[@"info1"];        _personname=info1[@"personname"];    } fail:^{        NSLog(@"請求失敗");    }];}

 

網上實現多圖片的上傳的教程幾乎沒,所以在這裡特別說下。方便別人學習。

首先看下瀏覽器端的上傳實現:http://www.w3school.com.cn/php/php_file_upload.asp

一般情況下for表單都是預設索引值對傳輸的,當表單類型設定為enctype="multipart/form-data"時,傳輸會按照二進位傳輸。

PHP後台和W3C教程基本一樣,我稍微改了下,用foreach就能實現動態單個檔案上傳或者多個檔案上傳了。

說明一下,上傳檔案都放在$_FILES的數組裡,擷取方式$_FILES["file0"]或者$_FILES["file1"],這個file0就是再下面iOS工程裡定義的name。

PHP後台代碼如下:

<?        header("Content-type: text/html; charset=UTF-8");    include("../configmysql.php");    mysql_select_db("chepaiDB",$q); //資料庫      //POST擷取索引值對參數    $TEMPid=$_POST[‘Driverid‘];    echo "\nDriverid is ".$TEMPid."\n";    foreach ($_FILES as $_eachFile) {        //file檔案處理        if ($_eachFile["error"] > 0)          {          echo "錯誤: " . $_eachFile["error"] . "\n";          }        else          {          echo "檔案名稱: " . $_eachFile["name"] . "\n";          echo "類型: " . $_eachFile["type"] . "\n";          echo "大小: " . ($_eachFile["size"] / 1024) . " Kb\n";           }         if (file_exists("uploadimage/" . $_eachFile["name"]))            {              echo $_eachFile["name"] . " 檔案已經存在. ";            }        else            {              move_uploaded_file($_eachFile["tmp_name"],              "uploadimage/" . $_eachFile["name"]);              echo "檔案已經被儲存到: " . "uploadimage/" . $_eachFile["name"]."\n";            }    }    /*    //file檔案處理    if ($_FILES["file"]["error"] > 0)      {      echo "錯誤: " . $_FILES["file"]["error"] . "\n";      }    else      {      echo "檔案名稱: " . $_FILES["file"]["name"] . "\n";      echo "類型: " . $_FILES["file"]["type"] . "\n";      echo "大小: " . ($_FILES["file"]["size"] / 1024) . " Kb\n";       }     if (file_exists("uploadimage/" . $_FILES["file"]["name"]))        {          echo $_FILES["file"]["name"] . " 檔案已經存在. ";        }    else        {          move_uploaded_file($_FILES["file"]["tmp_name"],          "uploadimage/" . $_FILES["file"]["name"]);          echo "檔案已經被儲存到: " . "uploadimage/" . $_FILES["file"]["name"]."\n";        }    */?>

在AFN架構裡,FORMDATA的體現,就是[manager POST:urlStr parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {}這個函數是專門用於formData上傳的,還可攜帶其他參數。

單圖上傳:

#pragma mark - 單個圖片上傳- (void)uploadimgWithurl:(NSString *)urlStr image:(UIImage *)image fileName:(NSString *)fileName success:(void (^)(id responseObject))success fail:(void (^)())fail{    //需要傳遞的參數,jason格式    NSDictionary *parameter = @{@"Driverid": @"10000"};    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];    manager.responseSerializer = [AFHTTPResponseSerializer serializer];    [manager POST:urlStr parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {        /*檔案命名參考代碼         // 在網路開發中,上傳檔案時,是檔案不允許被覆蓋,檔案重名         // 要解決此問題,         // 可以在上傳時使用當前的系統事件作為檔案名稱         NSDateFormatter *formatter = [[NSDateFormatter alloc] init];         // 設定時間格式         formatter.dateFormat = @"yyyyMMddHHmmss";         NSString *str = [formatter stringFromDate:[NSDate date]];         NSString *newfileName = [NSString stringWithFormat:@"%@.png", str];         */        [formData appendPartWithFileData:UIImagePNGRepresentation(image) name:@"file" fileName:fileName mimeType:@"image/png"];    } success:^(AFHTTPRequestOperation *operation, id responseObject) {        if (success) {            //NSLog(@"success\n");            success(responseObject);        }    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {        if (fail) {            //NSLog(@"fail\n");            fail();        }    }];}

調用:

//單圖片上傳-(void)uploadimg{    NSString *url = @"http://localhost:8888/chepaishibie/uploadimage.php";    UIImage *image=[UIImage imageNamed:@"swift"];    [[ShenAFN sharedInstance] uploadimgWithurl:url image:image fileName:@"myswift.png" success:^(id jsondata) {        NSString *result = [[NSString alloc] initWithData:jsondata encoding:NSUTF8StringEncoding];        NSLog(@"%@", result);    } fail:^{        NSLog(@"請求失敗");    }];}

 

多圖片上傳:主要是利用appendPartWithFileData函數,一個for迴圈把NSMutablearray裡的圖片都添加進去。

- (void)uploadMutableimgWithurl:(NSString *)urlStr imagearray:(NSMutableArray *)imgarray success:(void (^)(id responseObject))success fail:(void (^)())fail{    //需要傳遞的參數,jason格式    NSDictionary *parameter = @{@"Driverid": @"10000"};        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];    manager.responseSerializer = [AFHTTPResponseSerializer serializer];    [manager POST:urlStr parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {        /*檔案命名參考代碼         // 在網路開發中,上傳檔案時,是檔案不允許被覆蓋,檔案重名         // 要解決此問題,         // 可以在上傳時使用當前的系統事件作為檔案名稱         NSDateFormatter *formatter = [[NSDateFormatter alloc] init];         // 設定時間格式         formatter.dateFormat = @"yyyyMMddHHmmss";         NSString *str = [formatter stringFromDate:[NSDate date]];         NSString *newfileName = [NSString stringWithFormat:@"%@.png", str];         */        for (int i=0; i<[imgarray count]; i++) {            [formData appendPartWithFileData:UIImagePNGRepresentation([imgarray objectAtIndex:i]) name:[NSString stringWithFormat:@"file%d",i ] fileName:[NSString stringWithFormat:@"pic%d.png",i] mimeType:@"image/png"];        }    } success:^(AFHTTPRequestOperation *operation, id responseObject) {        if (success) {            //NSLog(@"success\n");            success(responseObject);        }    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {        if (fail) {            //NSLog(@"fail\n");            fail();        }    }];}

調用:

//多圖片上傳-(void)uploadmutableimg{    NSString *url = @"http://localhost:8888/chepaishibie/uploadimage.php";    UIImage *image1=[UIImage imageNamed:@"0"];    UIImage *image2=[UIImage imageNamed:@"1"];    NSMutableArray *imgarray=[[NSMutableArray alloc]init];    [imgarray addObject:image1];    [imgarray addObject:image2];        [[ShenAFN sharedInstance] uploadMutableimgWithurl:url imagearray:imgarray success:^(id jsondata) {        NSString *result = [[NSString alloc] initWithData:jsondata encoding:NSUTF8StringEncoding];        NSLog(@"%@", result);    } fail:^{        NSLog(@"請求失敗");    }];}

 

另外JPEG的圖片壓縮可以用:

UIImageJPEGRepresentation(image,0.5);

 

GITHUB:   https://github.com/rayshen/AFNDemo

 

[iOS AFNetworking架構實現HTTP請求、多檔案圖片上傳下載]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.