2014-10-09 58 views
1

我有一個應用程序,可以在Web服務器上上傳用戶數據。使用PHP在ios上通過JSON在web服務器上傳圖像

我正在使用下面的代碼將數據傳遞給webserver與下面的代碼。

-(IBAction)btnRegister:(id)sender 
{ 
    jsonSP = [SBJSON new]; 
    jsonSP.humanReadable = YES; 

    NSString *service = @"/register.php"; 
    NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@"register_btn.png"]); 
    [Base64 initialize]; 
    NSString *imageString = [Base64 encode:imageData]; 
    NSLog(@"%@",imageString); 


    NSString *requestString = [NSString stringWithFormat:@"{\"?username\"=\"%@\"&\"user_password\"=\"%@\"&\"first_name\"=\"%@\"&\"email\"=\"%@\"&\"profile_photo_link\"=\"%@\"\"}",@"Test",@"Test",@"Test",@"[email protected]",imageString]; 
    NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]]; 

    NSString *fileLoc = [[NSBundle mainBundle] pathForResource:@"URLName" ofType:@"plist"]; 
    NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc]; 
    NSString *urlLoc = [fileContents objectForKey:@"URL"]; 
    urlLoc = [urlLoc stringByAppendingString:service]; 
    NSLog(@"URL : %@",urlLoc); 
    // urlLoc = [urlLoc stringByAppendingString:@"?username=abcd&password=abcd"]; 
    urlLoc = [urlLoc stringByAppendingString:requestString]; 
    urlLoc = [urlLoc stringByReplacingOccurrencesOfString:@"{" withString:@""]; 
    urlLoc = [urlLoc stringByReplacingOccurrencesOfString:@"}" withString:@""]; 
    urlLoc = [urlLoc stringByReplacingOccurrencesOfString:@"\"" withString:@""]; 
    NSLog(@"URL : %@",urlLoc); 
    // [fileContents release]; //o_r 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]]; 
    NSString *postLength = [NSString stringWithFormat:@"%d", [requestData length]]; 
    [request setHTTPMethod: @"POST"]; 
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
    [request setHTTPBody: requestData]; 

    // self.connection = [NSURLConnection connectionWithRequest:request delegate:self]; 

    NSError *respError = nil; 
    NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ]; 
    NSLog(@"response is %@",returnData); 


    // [request release]; 
    if (respError) 
    { 
     //[customSpinner hide:YES]; 

     UIAlertView *alt=[[UIAlertView alloc]initWithTitle:@"Internet connection is not Available!" message:@"Check your network connectivity" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; 
     [alt show]; 
     //[alt release]; 


    } 
    else 
    { 
     NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding]; 
     NSLog(@"response string %@",responseString); 
    } 
} 

我成功地能夠發送數據到網絡服務器沒有圖像。

但是,如果通過編碼Base64上傳帶有上述代碼的圖像,則數據不會上傳到網絡服務器上。 它給我一個錯誤在NSLog說請求查詢字符串太長。

我已經導入Base64.h和.m文件。

我想通過圖像傳遞數據也。

我該怎麼做?

我知道有很多鏈接,但我想通過這種方式,所以請告訴我我在這裏做什麼錯了?

請幫幫我。

在此先感謝。

回答

0

我做了它與多部分形式的數據下面的代碼工作。

responseData = [NSMutableData data]; 
    NSString *service = @"http:///registerUser.php"; 

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
    [request setURL:[NSURL URLWithString:service]]; 
    [request setHTTPMethod:@"POST"]; 

//創建一個boundry ...

NSString *boundary = @"---------------------------14737809831466499882746641449"; 
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; 
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; 

//創建後的身體

NSMutableData *body = [NSMutableData data]; 
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[@"Content-Disposition: form-data; name=\"profile_photo_link\"; filename=\"ipodfile.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 

UIImageView *imgvUserImage = [[UIImageView alloc]init]; 
    imgvUserImage.image= [UIImage imageNamed:@"register_btn.png"]; 

    NSData * imageData=[NSData dataWithData:UIImagePNGRepresentation(imgvUserImage.image)]; 

    [body appendData:[NSData dataWithData:imageData]]; 
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 


[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"username\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 

    [body appendData:[[NSString stringWithFormat:@"%@",txtUserName.text] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 

//後的身體設置爲reqeust

[request setHTTPBody:body]; 
    postconnection=[[NSURLConnection alloc] initWithRequest:request delegate:self]; 

**對於回覆

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    [responseData setLength:0]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    [responseData appendData:data]; 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    [self removeProgressIndicator]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    if (connection == postconnection) 
    { 
     NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
     NSLog(@"%@",responseString); 
     // NSDictionary *deserializedData = [responseString objectFromJSONString]; 
     // NSString *string = [deserializedData objectForKey:@"Status"]; 


    } 
} 
0

嘿Manthan嘗試使用轉換UIImage這種波紋管代碼NSString,然後將它傳遞給服務器

 UIImage *imgPic =[UIImage imageNamed:@"register_btn.png"]; 
     NSData * imageData = UIImagePNGRepresentation(imgPic); 
     NSString *base64String = [imageData base64EncodedStringWithOptions:0]; 
+0

感謝哥們。我會檢查它並讓你知道。 – Manthan 2014-10-10 05:33:51

+0

我仍然得到請求字符串的錯誤信息太長,因爲我在NSLog中得到了太長的base64String。 – Manthan 2014-10-10 05:48:05

+0

你是否知道如何通過多路徑數據發送圖像?如果是的話,請幫助。免費幫助kar ne bhai。 – Manthan 2014-10-21 06:48:21

0

它的服務器問題,它告訴你的錯誤。

json沒有最大長度,但是可以發送的數據量最大。爲了解決這個問題,只需設置數據,你可以在.htaccess文件發送量:php_value post_max_size 20M

編輯

另外,如果你有機會到php.ini文件,你可以在

post_max_size行更改
+0

@o Pi:所以我的代碼是正確的,但在Web服務器端,我需要對其進行更改。好? – Manthan 2014-10-10 07:34:57

+0

@Manthan它不是你的代碼,它的服務器配置 – 2014-10-10 07:35:26

+0

我的意思是在上面的代碼中,我不需要改變任何東西,但只在服務器端代碼。 – Manthan 2014-10-10 08:49:26

0

試試這個;

- (void)addNewItem:(SH_NewItem *)newItem withCompletitionBlock:(void(^)(NSArray *items, NSError *error, NSDictionary *userInfo))completitionBlock 
{ 
    AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:[[SH_Shared sharedInstance] getBaseURL]]]; 

    //main cover image... 
    NSData *imageData = UIImageJPEGRepresentation(newItem.image, JPEG_IMAGE_QUALITY); 


    NSData *imageData1 = UIImageJPEGRepresentation(newItem.image1, JPEG_IMAGE_QUALITY); 
    NSData *imageData2 = UIImageJPEGRepresentation(newItem.image2, JPEG_IMAGE_QUALITY); 
    NSData *imageData3 = UIImageJPEGRepresentation(newItem.image3, JPEG_IMAGE_QUALITY); 
    NSData *imageData4 = UIImageJPEGRepresentation(newItem.image4, JPEG_IMAGE_QUALITY); 

    NSDictionary *params = [[NSDictionary alloc]init]; 

    params = [NSDictionary dictionaryWithObjectsAndKeys: 
          newItem.title, @"title", 
          newItem.itemDescription, @"description", 
          [[SH_Shared sharedInstance] token], @"token", 
          nil]; 

    NSLog(@"params-%@",params); 

    NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"new_item" parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData> formData) { 
     if (imageData != nil) 
      [formData appendPartWithFileData:imageData name:@"images[0]" fileName:@"image_ad.png" mimeType:@"multipart/form-data"]; 


     if (imageData1 != nil) 
      [formData appendPartWithFileData:imageData1 name:@"images[1]" fileName:@"image_ad1.png" mimeType:@"multipart/form-data"]; 
     if (imageData2 != nil) 
      [formData appendPartWithFileData:imageData2 name:@"images[2]" fileName:@"image_ad2.png" mimeType:@"multipart/form-data"]; 
     if (imageData3 != nil) 
      [formData appendPartWithFileData:imageData3 name:@"images[3]" fileName:@"image_ad3.png" mimeType:@"multipart/form-data"]; 
     if (imageData4 != nil) 
      [formData appendPartWithFileData:imageData4 name:@"images[4]" fileName:@"image_ad4.png" mimeType:@"multipart/form-data"]; 

    }]; 


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

    [self getDataWithOperation:op completitionBlock:^(NSData *data, NSError *error, NSDictionary *userInfo) { 
     CJSONDeserializer *deserializer = [CJSONDeserializer deserializer]; 

     NSError *deserializeError = nil; 

     NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 

     NSLog(@"Response: %@", str); 


    NSDictionary *requestResponseDict = [deserializer deserialize:data error:&deserializeError]; 

     NSString *status = [requestResponseDict valueForKey:kStatus]; 

     BOOL isSuccess = [[status valueForKey:kSuccess] boolValue]; 

     if (isSuccess) 
     { 
      // it's OK 

     } 
     else 
     { 
      // its error 
     } 
    }]; 
} 
相關問題