フォーム用AFNetWorkingの発行

9188 ワード

直接コード:
 // 
-(void)importDate:(UIButton *)button {


    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:_count,@"count",_productId,@"Id", nil];

    AFHTTPRequestOperationManager* mgr = [AFHTTPRequestOperationManager manager];


    // 
    [mgr POST:E_returnGoodsDetailURL parameters:dic constructingBodyWithBlock:^(id totalformData) {



        for (int i = 0; i<_imagearr class="hljs-variable">.count; i++) {

            [totalformData appendPartWithFileData:[_imageArr objectAtIndex:i] name:[NSString stringWithFormat:@"image%i",i] fileName:[NSString stringWithFormat:@"image%i.jpg",i] mimeType:@"image/jpeg"];
        }


    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        // 
        NSLog(@" ====%@",responseObject);

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

    } ];



}

原理部分では、ネット上でブロガーの文章を見ました.
1、ネットワーク要求によく使われるのはGet要求、Post要求、そしてHead、Put、Delete、Options、Trace、ConnectなどのGETが指定リソースPOSTを取得して指定リソースにデータを提出して処理要求を行う、RESTfulスタイルでの新規リソースHEAD取得指定リソースヘッダ情報PUT置換指定リソース(ブラウザ操作はサポートされていません)DELETE削除指定リソースOPTIONSクライアントがサーバのパフォーマンスTRACEエコーサーバから受信した要求を表示できるようにします.主にCONNECTをテストまたは診断して接続をパイプ方式に変更できるプロキシサーバ(HTTPエージェント使用)に予約するために使用されます.
2、アップロード画像はウェブページで最もよく使われるのはPOST要求であり、POST要求体(body)に画像を符号化し、要求データとともにサーバに送信する.
3、iOSの开発では、画像のアップロードの要求体は非常に难しく、フォーマットの要求は非常に厳格で、少しのエラーが発生してもアップロードに失败したり、データの要求に失败したりします.まずフォーマットを见てください.-Boundary+72 D 4 CD 655314 C 423 Content-Disposition:form-data;name=”uploadFile”; filename=”001.png” Content-Type:image/png Content-Transfer-Encoding: binary
… contents of boris.png...–Boundary+72 D 4 CD 655314 C 423–これは他のタスクパラメータを持たないで、bodyの中で1枚の図だけをこのように書いて説明します:–Boundary+72 D 4 CD 655314 C 423//分割子、「-」で始まり、後ろの字は勝手に書いて、中国語を書かない限りContent-Disposition:form-data;name=”uploadFile”; filename=”001.png"//ここにサーバが画像を受信するパラメータ(受信ユーザ名のuserNameに類似)とサーバ上に画像を保存するファイル名Content-Type:image/png//画像タイプpng Content-transfer-Encoding:binary//符号化方式//ここは空の行で、必ず少なくない!!!contents of boris.png...//ピクチャデータ部分–Boundary+72 D 4 CD 655314 C 423-//区切り記号の後に「-」で終わり、終了を示す
3、ユーザーIDなどの他のフォームデータがある場合は、-Boundary+72 D 4 CD 655314 C 423 Content-Disposition:form-data;name=”userId”
254 –Boundary+72D4CD655314C423 Content-Disposition: form-data; name=”shopId”
18718具体的なパラメータの意味は画像と一致しており、一般的にはこの段落は画像の上にあるので、末尾文字はありません.他のデータがなければ、末尾文字を付けます.
4、コード例:-(void)upload{NSString*urlStr=@"http://localhost/upload.php“; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr] cachePolicy:0 timeoutInterval:5.0f];
[self setRequest:request];

NSLog(@" ...");
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

    NSLog(@"Result--%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

}];

}
  • (void)setRequest:(NSMutableURLRequest*)request{NSString*boundary=[NSString stringWithFormat:@"Boundary+%08 X%08 X",arc 4 random(),arc 4 random();NSMutableData*body=[NSMutableData data];////////フォームデータNSMutableDictionary*param=[NSMutableDictionary alloc] init];[param setValue:@"@"@"@"@""@"""@"@"""=[NSMutableVaam setValue:@"@"@""@""""254"forKey:@"empId";[param setValue:@"18718"forKey:@"shopId"];/** 辞書を巡回して辞書のキー値ペアを要求フォーマットに変換します:–Boundary+72 D 4 CD 655314 C 423 Content-Disposition:form-data;name=”empId” 254 –Boundary+72D4CD655314C423 Content-Disposition: form-data; name=”shopId” 18718 */ [param enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { NSMutableString *fieldStr = [NSMutableString string]; [fieldStr appendString:[NSString stringWithFormat:@”–%@\r”, boundary]]; [fieldStr appendString:[NSString stringWithFormat:@”Content-Disposition: form-data; name=\”%@\”\r\r”, key]]; [fieldStr appendString:[NSString stringWithFormat:@”%@”, obj]]; [body appendData:[fieldStr dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@”\r” dataUsingEncoding:NSUTF8StringEncoding]]; }];///画像データ部NSMutablesString*topStr=[NSMutablesString string];NSString *path = [[NSBundle mainBundle] pathForResource:@”001.jpg” ofType:nil]; NSData *data = [NSData dataWithContentsOfFile:path];/**組込みフォーマット:–Boundary+72 D 4 CD 655314 C 423 Content-Disposition:form-data;name=”uploadFile”; filename=”001.png” Content-Type:image/png Content-Transfer-Encoding: binary … contents of boris.png … */ [topStr appendString:[NSString stringWithFormat:@”–%@\r”, boundary]]; [topStr appendString:@”Content-Disposition: form-data; name=\”uploadFile\”; filename=\”001.png\”\r”]; [topStr appendString:@”Content-Type:image/png\r”]; [topStr appendString:@”Content-Transfer-Encoding: binary\r\r”]; [body appendData:[topStr dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:data]; [body appendData:[@”\r” dataUsingEncoding:NSUTF8StringEncoding]];//終了部NSString*bottomStr=[NSString stringWithFormat:@]-%@-」,boundary;/**組込み形式:–Boundary+72 D 4 CD 655314 C 423–*/[body appendData:[bottomStr dataUsingEncoding:NSUTF 8 StringEncoding];//リクエストタイプをpostリクエストrequestに設定.HTTPMethod = @”post”; //リクエストのリクエスト体requestを設定.HTTPBody = body; //ヘッダデータを設定し、アップロードデータの合計サイズを明記し、サーバ受信検証に使用する[request setValue:[NSString stringWithFormat:@]%d",body.length]forHTTPHeaderField:@"Content-Longth";//ヘッダデータを設定し、http postリクエストの符号化方法をmultipart/form-dataと指定します(アップロードファイルはこれを使用する必要があります).[request setValue:[NSString stringWithFormat:@”multipart/form-data; boundary=%@”,boundary] forHTTPHeaderField:@”Content-Type”]; }

  • 複数の画像をループアップロードすると、次のようになります.
    NSMutableString *topStr = [NSMutableString string];
        NSString *path = [[NSBundle mainBundle] pathForResource:@"001.jpg" ofType:nil];
        NSData *data = [NSData dataWithContentsOfFile:path];
    
        /** :
         --Boundary+72D4CD655314C423
         Content-Disposition: form-data; name="uploadFile"; filename="001.png"
         Content-Type:image/png
         Content-Transfer-Encoding: binary
    
         ... contents of boris.png ...
         */
        [topStr appendString:[NSString stringWithFormat:@"--%@\r
    "
    , boundary]]; [topStr appendString:@"Content-Disposition: form-data; name=\"uploadFile\"; filename=\"001.png\"\r
    "
    ]; [topStr appendString:@"Content-Type:image/png\r
    "
    ]; [topStr appendString:@"Content-Transfer-Encoding: binary\r
    \r
    "
    ]; [body appendData:[topStr dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:data]; [body appendData:[@"\r
    "
    dataUsingEncoding:NSUTF8StringEncoding]];

    forループに書く(ピクチャの初期化やリクエストヘッダやリクエストの変換は、初期化にも注意して書く)
    //  
        NSString *bottomStr = [NSString stringWithFormat:@"--%@--", boundary];
        /** :
         --Boundary+72D4CD655314C423--
         */
        [body appendData:[bottomStr dataUsingEncoding:NSUTF8StringEncoding]];
    
        //  post 
        request.HTTPMethod = @"post";
        //  request 
        request.HTTPBody = body;
        //  , , 
        [request setValue:[NSString stringWithFormat:@"%d", body.length] forHTTPHeaderField:@"Content-Length"];
        //  , http post multipart/form-data( )。
        [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary] forHTTPHeaderField:@"Content-Type"];

    (終了部および以下の要求は循環体の外に書く)