1. 程式人生 > >iOS多圖片上傳

iOS多圖片上傳

開始學習Objc20多天了,最近在弄多檔案上傳,在網上找了些程式碼,只是單檔案的,折騰了兩天,終於改成多檔案上傳的了。
xcode 6.1
iOS 8.0測試成功
希望別的人不要像我一樣花時間在修改上。時間就是生命啊。。

+(NSString *)PostImagesToServer:(NSString *) strUrl dicPostParams:(NSMutableDictionary *)params dicImages:(NSMutableDictionary *) dicImages{
    NSString * res;
    
    
    //分界線的識別符號
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //根據url初始化request
    //NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strUrl] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //分界線 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //結束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //要上傳的圖片
    UIImage *image;//=[params objectForKey:@"pic"];
    //得到圖片的data
    //NSData* data = UIImagePNGRepresentation(image);
    //http body的字串
    NSMutableString *body=[[NSMutableString alloc]init];
    //引數的集合的所有key的集合
    NSArray *keys= [params allKeys];
    
    //遍歷keys
    for(int i=0;i<[keys count];i++) {
        //得到當前key
        NSString *key=[keys objectAtIndex:i];
        //如果key不是pic,說明value是字元型別,比如name:Boris
        //if(![key isEqualToString:@"pic"]) {
            //新增分界線,換行
            [body appendFormat:@"%@\r\n",MPboundary];
            //新增欄位名稱,換2行
            [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
            //[body appendString:@"Content-Transfer-Encoding: 8bit"];
            //新增欄位的值
            [body appendFormat:@"%@\r\n",[params objectForKey:key]];
        //}
    }
    ////新增分界線,換行
    //[body appendFormat:@"%@\r\n",MPboundary];
    
    //宣告myRequestData,用來放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //將body字串轉化為UTF8格式的二進位制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    
    //迴圈加入上傳圖片
    keys = [dicImages allKeys];
    for(int i = 0; i< [keys count] ; i++){
        //要上傳的圖片
        image = [dicImages objectForKey:[keys objectAtIndex:i ]];
        //得到圖片的data
        NSData* data =  UIImageJPEGRepresentation(image, 0.0);
        NSMutableString *imgbody = [[NSMutableString alloc] init];
        //此處迴圈新增圖片檔案
        //新增圖片資訊欄位
        //宣告pic欄位,檔名為boris.png
        //[body appendFormat:[NSString stringWithFormat: @"Content-Disposition: form-data; name=\"File\"; filename=\"%@\"\r\n", [keys objectAtIndex:i]]];
        
        ////新增分界線,換行
        [imgbody appendFormat:@"%@\r\n",MPboundary];
        [imgbody appendFormat:@"Content-Disposition: form-data; name=\"File%d\"; filename=\"%@.jpg\"\r\n", i, [keys objectAtIndex:i]];
        //宣告上傳檔案的格式
        [imgbody appendFormat:@"Content-Type: application/octet-stream; charset=utf-8\r\n\r\n"];
        
        NSLog(@"上傳的圖片:%d  %@", i, [keys objectAtIndex:i]);
        
        //將body字串轉化為UTF8格式的二進位制
        //[myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
        [myRequestData appendData:[imgbody dataUsingEncoding:NSUTF8StringEncoding]];
        //將image的data加入
        [myRequestData appendData:data];
        [myRequestData appendData:[ @"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    }
    //宣告結束符:--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"%@\r\n",endMPboundary];
    //加入結束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //設定HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //設定HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //[request setValue:@"keep-alive" forHTTPHeaderField:@"connection"];
    //[request setValue:@"UTF-8" forHTTPHeaderField:@"Charsert"];
    //設定Content-Length
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //設定http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    
    //建立連線,設定代理
    //NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    //設定接受response的data
         NSData *mResponseData;
    NSError *err = nil;
    mResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&err];
    
    if(mResponseData == nil){
        NSLog(@"err code : %@", [err localizedDescription]);
    }
    res = [[NSString alloc] initWithData:mResponseData encoding:NSUTF8StringEncoding];
    /*
    if (conn) {
        mResponseData = [NSMutableData data];
        mResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&err];
        
        if(mResponseData == nil){
            NSLog(@"err code : %@", [err localizedDescription]);
        }
        res = [[NSString alloc] initWithData:mResponseData encoding:NSUTF8StringEncoding];
    }else{
        res = [[NSString alloc] init];
    }*/
    NSLog(@"伺服器返回:%@", res);
    return res;
}