2016-10-25 8 views
0

Загрузить массив из images и string параметров на сервер
, чтобы загрузить массив изображений и строку. Я использую этот подход, но только Я могу загрузить single image, что является первым. И другие изображения массива не загружаяКак загрузить массив изображений и строковые параметры на сервер?

[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; 
      [request setHTTPShouldHandleCookies:NO]; 
      [request setTimeoutInterval:30]; 
      [request setHTTPMethod:action_type]; 



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



      NSMutableData *body = [NSMutableData data]; 

    if([param isEqualToString:kprofile_pic]) 
       { 

        //Photo 
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
        [body appendData:[@"Content-Disposition: form-data; name=\"photo[]\"; filename=\"image.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
        [body appendData:[@"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
        [body appendData:[dictionary objectForKey:param]]; 
        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 

       } 
       else 
       { 

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

       } 


      } 


      [request setHTTPBody:body]; 

ответ

0

Если счетчик массива фиксирован, то вы можете добавить изображение к телу соответственно. Но если подсчет массива не фиксирован или он динамический, отправьте изображение один за другим на сервере. Проверьте следующее:

-(void)uploadimage 
{ 
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"yyyyMMddHHmmss"]; 
    NSDate *now = [[NSDate alloc] init]; 
    NSString *theDate = [dateFormat stringFromDate:now]; 
    NSLog(@"\n" 
      "theDate: |%@| ", theDate); 
    UIImage *image = [imagearray objectAtIndex:imagecount]; 
    imagecount++; 


    NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, 0.7f)]; 


    NSURL *dataURL = [NSURL URLWithString:baseurl]; 

    NSMutableURLRequest *dataRqst = [NSMutableURLRequest requestWithURL:dataURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]; 

    [dataRqst setHTTPMethod:@"POST"]; 

    NSString *stringBoundary = @"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo"; 
    NSString *headerBoundary = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",stringBoundary]; 

    [dataRqst addValue:headerBoundary forHTTPHeaderField:@"Content-Type"]; 

    NSMutableData *postBody = [NSMutableData data]; 


    [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"%@\"\r\n",[NSString stringWithFormat:@"%@.png",theDate]] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [postBody appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
    [postBody appendData:imageData]; 
    [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 

    [postBody appendData:[[NSString stringWithFormat:@"--%@--\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [dataRqst setHTTPBody:postBody]; 

    NSHTTPURLResponse* response =[[NSHTTPURLResponse alloc] init]; 
    NSError* error = nil ; 
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:dataRqst delegate:self]; 

    } 

#pragma mark NSURLConnection Delegate Methods 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    self.receiveData = [[NSMutableData alloc] init]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    [self.receiveData appendData:data]; 

    NSError* error; 
    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data 
                 options:kNilOptions 
                  error:&error]; 
    NSLog(@"json..%@",json); 
    if (imagecount <[imagearray count]) { 
     [self uploadimage]; 
    } 
    else 
    { 

       UIAlertView *alert= [[UIAlertView alloc] initWithTitle:nil 
                   message:@"Data uploaded successfully" 
                   delegate:nil 
                 cancelButtonTitle:nil 
                 otherButtonTitles:nil, nil] ; 
       [alert show]; 
    } 

} 

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection 
        willCacheResponse:(NSCachedURLResponse*)cachedResponse { 
    return nil; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
} 

-(void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite 
{ 
} 
+0

здесь, где и загружает массив изображений .. ??? –

+0

Возьмите один int, предположим int imagecount = 0 в начале; Затем назовите [self uploadimage]; И затем проверьте - (void) соединение: (NSURLConnection *) connection didReceiveData: (NSData *) data В этом методе мы проверяем, будет ли количество изображений равным количеству массивов. –

+0

, но u r appending imageData где [uploadimage] –

0
#import "tesstt.h" 
#import "HttpRequest.h" 
@interface tesstt() 
{ 
    int imagecount; 
} 
@property(nonatomic,retain)NSMutableData *receiveData; 
@property(nonatomic,retain)NSMutableArray *imagearray; 

@end 

@implementation tesstt 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
} 

-(IBAction)submit:(id)sender 
{ 
    imagecount = 0; 
    [self uploadimage]; 
} 
-(void)uploadimage 
{ 
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"yyyyMMddHHmmss"]; 
    NSDate *now = [[NSDate alloc] init]; 
    NSString *theDate = [dateFormat stringFromDate:now]; 
    NSLog(@"\n" 
      "theDate: |%@| ", theDate); 
    UIImage *image = [self.imagearray objectAtIndex:imagecount]; 
    imagecount++; 


    NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, 0.7f)]; 

    NSString *baseurl = @""; 

    NSURL *dataURL = [NSURL URLWithString:baseurl]; 

    NSMutableURLRequest *dataRqst = [NSMutableURLRequest requestWithURL:dataURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]; 

    [dataRqst setHTTPMethod:@"POST"]; 

    NSString *stringBoundary = @"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo"; 
    NSString *headerBoundary = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",stringBoundary]; 

    [dataRqst addValue:headerBoundary forHTTPHeaderField:@"Content-Type"]; 

    NSMutableData *postBody = [NSMutableData data]; 


    [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"%@\"\r\n",[NSString stringWithFormat:@"%@.png",theDate]] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [postBody appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
    [postBody appendData:imageData]; 
    [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 

    [postBody appendData:[[NSString stringWithFormat:@"--%@--\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [dataRqst setHTTPBody:postBody]; 

    NSHTTPURLResponse* response =[[NSHTTPURLResponse alloc] init]; 
    NSError* error = nil ; 
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:dataRqst delegate:self]; 

} 

#pragma mark NSURLConnection Delegate Methods 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    self.receiveData = [[NSMutableData alloc] init]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    [self.receiveData appendData:data]; 

    NSError* error; 
    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data 
                 options:kNilOptions 
                  error:&error]; 
    NSLog(@"json..%@",json); 
    if (imagecount <[self.imagearray count]) { 
     [self uploadimage]; 
    } 
    else 
    { 

     UIAlertView *alert= [[UIAlertView alloc] initWithTitle:nil 
                 message:@"Data uploaded successfully" 
                 delegate:nil 
               cancelButtonTitle:nil 
               otherButtonTitles:nil, nil] ; 
     [alert show]; 
    } 

} 

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection 
        willCacheResponse:(NSCachedURLResponse*)cachedResponse { 
    return nil; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
} 

-(void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite 
{ 
} 
@end 
+0

У меня есть массив изображений, и я хочу отправить службу на один клик, является ли ур кодом для передачи изображений одним кликом или по одному? @Minkle Garg –