2012-05-16 19 views
5

Merhaba ben php sunucu üzerinde resim yükleyerek ve başarıyla bu koduiOS'ta görüntü yükleme koduyla daha fazla parametre nasıl gönderilir?

- (NSString*)uploadData:(NSData *)data toURL:(NSString *)urlStr:(NSString *)_userID 
{ 
    // File upload code adapted from http://www.cocoadev.com/index.pl?HTTPFileUpload 
    // and http://www.cocoadev.com/index.pl?HTTPFileUploadSample 
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; 
    [request setURL:[NSURL URLWithString:urlStr]]; 
    [request setHTTPMethod:@"POST"]; 

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


    NSMutableData *body = [NSMutableData data]; 
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
// [body appendData:[[NSString stringWithFormat:@"userId=%@",_userID] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"image%@.jpg\"\r\n", _userID] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[NSData dataWithData:data]]; 
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    // setting the body of the post to the reqeust 
    [request setHTTPBody:body]; 

    // now lets make the connection to the web 
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; 

    NSLog(@"%@",returnString); 

    return returnString; 

} 

Şimdi ben benim kullanıcı kimliği gönderebilir nasıl derver tarafta da benim kullanıcıyı Kimliği göndermek istediğiniz yardımıyla yüklendi ben? Ben

[body appendData:[[NSString stringWithFormat:@"userId=%@",_userID] dataUsingEncoding:NSUTF8StringEncoding]]; 

bu şekilde onunla çalıştı ama boşuna sonra ben çok nazikçe ne yapacağını bana yol boşuna bu şekilde tekrar

[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"image%@.jpg\"; userId=\"%@\"\r\n", _userID, _userID] dataUsingEncoding:NSUTF8StringEncoding]]; 

ama göndermek için çalıştı!

+0

Lütfen php ve ios'un çalışma kodunu paylaşır mısınız? –

cevap

4

Eğer AFNetworking kullanımı hakkında size gerektiğini düşündüm yoksa. Web servisleri ile uğraşmayı çok daha kolaylaştırıyor. Yapmak istediğini düşündüğüm şeye benzer bir şey yaptım. Ağ isteklerini kapatmak için özel bir sınıf yazdım. Al bakalım: NetworkClient.h

/* 
NetworkClient.h 

Created by LJ Wilson on 2/3/12. 
Copyright (c) 2012 LJ Wilson. All rights reserved. 
License: 

Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
and associated documentation files (the "Software"), to deal in the Software without restriction, 
including without limitation the rights to use, copy, modify, merge, publish, distribute, 
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 
furnished to do so, subject to the following conditions: 

The above copyright notice and this permission notice shall be included in all copies or 
substantial portions of the Software. 

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT 
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT 
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
*/ 

#import <Foundation/Foundation.h> 

extern NSString * const APIKey; 

@interface NetworkClient : NSObject 

+(void)processURLRequestWithURL:(NSString *)url 
         andParams:(NSDictionary *)params 
          block:(void (^)(id obj))block; 

+(void)processURLRequestWithURL:(NSString *)url 
         andParams:(NSDictionary *)params 
        syncRequest:(BOOL)syncRequest 
          block:(void (^)(id obj))block; 

+(void)processURLRequestWithURL:(NSString *)url 
         andParams:(NSDictionary *)params 
        syncRequest:(BOOL)syncRequest 
      alertUserOnFailure:(BOOL)alertUserOnFailure 
          block:(void (^)(id obj))block; 

+(void)processFileUploadRequestWithURL:(NSString *)url 
          andParams:(NSDictionary *)params 
           fileData:(NSData *)fileData 
           fileName:(NSString *)fileName 
           mimeType:(NSString *)mimeType 
           block:(void (^)(id obj))block; 

+(void)handleNetworkErrorWithError:(NSError *)error; 

+(void)handleNoAccessWithReason:(NSString *)reason; 

@end 

NetworkClient.m

/* 
NetworkClient.m 

Created by LJ Wilson on 2/3/12. 
Copyright (c) 2012 LJ Wilson. All rights reserved. 
License: 

Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
and associated documentation files (the "Software"), to deal in the Software without restriction, 
including without limitation the rights to use, copy, modify, merge, publish, distribute, 
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 
furnished to do so, subject to the following conditions: 

The above copyright notice and this permission notice shall be included in all copies or 
substantial portions of the Software. 

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT 
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT 
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
*/ 

#import "NetworkClient.h" 
#import "AFHTTPClient.h" 
#import "AFHTTPRequestOperation.h" 
#import "SBJson.h" 

NSString * const APIKey = @"APIKEY GOES HERE IF YOU WANT TO USE ONE"; 

@implementation NetworkClient 

+(void)processURLRequestWithURL:(NSString *)url 
         andParams:(NSDictionary *)params 
          block:(void (^)(id obj))block { 

    [self processURLRequestWithURL:url andParams:params syncRequest:NO alertUserOnFailure:NO block:^(id obj) { 
     block(obj); 
    }]; 
} 

+(void)processURLRequestWithURL:(NSString *)url 
         andParams:(NSDictionary *)params 
        syncRequest:(BOOL)syncRequest 
          block:(void (^)(id obj))block { 
    [self processURLRequestWithURL:url andParams:params syncRequest:syncRequest alertUserOnFailure:NO block:^(id obj) { 
     block(obj); 
    }]; 
} 


+(void)processURLRequestWithURL:(NSString *)url 
         andParams:(NSDictionary *)params 
        syncRequest:(BOOL)syncRequest 
      alertUserOnFailure:(BOOL)alertUserOnFailure 
          block:(void (^)(id obj))block { 

    // Default url goes here, pass in a nil to use it 
    if (url == nil) { 
     url = @"http://www.mydomain.com/mywebservice"; 
    } 

    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:params]; 
    [dict setValue:APIKey forKey:@"APIKey"]; 

    NSDictionary *newParams = [[NSDictionary alloc] initWithDictionary:dict]; 

    NSURL *requestURL; 
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:requestURL]; 

    NSMutableURLRequest *theRequest = [httpClient requestWithMethod:@"POST" path:url parameters:newParams]; 

    __block NSString *responseString = [NSString stringWithString:@""]; 

    AFHTTPRequestOperation *_operation = [[AFHTTPRequestOperation alloc] initWithRequest:theRequest]; 
    __weak AFHTTPRequestOperation *operation = _operation; 

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
     responseString = [operation responseString]; 

     id retObj = [responseString JSONValue]; 

     // Check for invalid response (No Access) 
     if ([retObj isKindOfClass:[NSDictionary class]]) { 
      if ([[(NSDictionary *)retObj valueForKey:@"Message"] isEqualToString:@"No Access"]) { 
       block(nil); 
       [self handleNoAccessWithReason:[(NSDictionary *)retObj valueForKey:@"Reason"]]; 
      } 
     } else if ([retObj isKindOfClass:[NSArray class]]) { 
      if ([(NSArray *)retObj count] > 0) { 
       NSDictionary *dict = [(NSArray *)retObj objectAtIndex:0]; 
       if ([[dict valueForKey:@"Message"] isEqualToString:@"No Access"]) { 
        block(nil); 
        [self handleNoAccessWithReason:[(NSDictionary *)retObj valueForKey:@"Reason"]]; 
       } 
      } 
     } 
     block(retObj); 
    } 
             failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
              NSLog(@"Failed with error = %@", [NSString stringWithFormat:@"[Error]:%@",error]); 
              block(nil); 
              if (alertUserOnFailure) { 
               // Let the user know something went wrong 
               [self handleNetworkErrorWithError:operation.error]; 
              } 

             }]; 

    [operation start]; 

    if (syncRequest) { 
     // Process the request syncronously 
     [operation waitUntilFinished]; 
    } 


} 


#pragma mark - processFileUpload 
+(void)processFileUploadRequestWithURL:(NSString *)url 
          andParams:(NSDictionary *)params 
           fileData:(NSData *)fileData 
           fileName:(NSString *)fileName 
           mimeType:(NSString *)mimeType 
           block:(void (^)(id obj))block { 

    // Default url goes here, pass in a nil to use it 
    if (url == nil) { 
     url = @"http://www.mydomain.com/mywebservice"; 
    } 

    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:params]; 
    [dict setValue:APIKey forKey:@"APIKey"]; 

    NSDictionary *newParams = [[NSDictionary alloc] initWithDictionary:dict]; 
    AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:url]]; 

    NSMutableURLRequest *myRequest = [client multipartFormRequestWithMethod:@"POST" 
                     path:@"" 
                   parameters:newParams 
                constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) { 
     [formData appendPartWithFileData:fileData name:fileName fileName:fileName mimeType:mimeType]; 
    }]; 


    AFHTTPRequestOperation *_operation = [[AFHTTPRequestOperation alloc] initWithRequest:myRequest]; 
    __weak AFHTTPRequestOperation *operation = _operation; 
    __block NSString *responseString = [NSString stringWithString:@""]; 

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
     responseString = [operation responseString]; 

     id retObj = [responseString JSONValue]; 

     // Check for invalid response (No Access) 
     if ([retObj isKindOfClass:[NSDictionary class]]) { 
      if ([[(NSDictionary *)retObj valueForKey:@"Message"] isEqualToString:@"No Access"]) { 
       block(nil); 
       [self handleNoAccessWithReason:[(NSDictionary *)retObj valueForKey:@"Reason"]]; 
      } 
     } else if ([retObj isKindOfClass:[NSArray class]]) { 
      if ([(NSArray *)retObj count] > 0) { 
       NSDictionary *dict = [(NSArray *)retObj objectAtIndex:0]; 
       if ([[dict valueForKey:@"Message"] isEqualToString:@"No Access"]) { 
        block(nil); 
        [self handleNoAccessWithReason:[(NSDictionary *)retObj valueForKey:@"Reason"]]; 
       } 
      } 
     } 
     block(retObj); 


    } 
             failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
              NSLog(@"Failed with error = %@", [NSString stringWithFormat:@"[Error]:%@",error]); 
              block(nil); 
//           if (alertUserOnFailure) { 
//            // Let the user know something went wrong 
//            [self handleNetworkErrorWithError:operation.error]; 
//           } 

             }]; 

    [operation start]; 


} 


#pragma mark - Error and Access Handling 
+(void)handleNetworkErrorWithError:(NSError *)error { 
    NSString *errorString = [NSString stringWithFormat:@"[Error]:%@",error]; 

    // Standard UIAlert Syntax 
    UIAlertView *myAlert = [[UIAlertView alloc] 
          initWithTitle:@"Connection Error" 
          message:errorString 
          delegate:nil 
          cancelButtonTitle:@"OK" 
          otherButtonTitles:nil, nil]; 

    [myAlert show]; 

} 

+(void)handleNoAccessWithReason:(NSString *)reason { 
    // Standard UIAlert Syntax 
    UIAlertView *myAlert = [[UIAlertView alloc] 
          initWithTitle:@"No Access" 
          message:reason 
          delegate:nil 
          cancelButtonTitle:@"OK" 
          otherButtonTitles:nil, nil]; 

    [myAlert show]; 

} 


@end 

bu bazıları benim yaptığım özeldir. Tüm web hizmetlerim güvenliği artırmak için bir APIKey kullanıyor ve tüm istekleri işlemeye başlamadan önce güvenlik kontrolleri yapıyorlar. Ağ istemcisi, web hizmetinin ne döndüğüne (JSON) bağlı olarak bir NSDictionary veya NSArray döndürür.

görüntü aktarma özelliğini kullanmak için, size

NSData *imageData = UIImagePNGRepresentation(myImage); 
NSString *fileName = @"MyFileName.png"; 

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: 
          @"Param1", @"Param1Name", 
          @"Param2", @"Param2Name", 
          @"Param3", @"Param3Name", 
          nil]; 
// Uses default URL  
[NetworkClient processFileUploadRequestWithURL:nil 
            andParams:params 
             fileData:imageData 
             fileName:fileName 
             mimeType:@"image/png" 
              block:^(id obj) { 
    if ([obj isKindOfClass:[NSArray class]]) { 
     // Successful upload, do other processing as needed 
    } 
}]; 

İhtiyacınız olmayan ne şerit çekinmeyin .: ihtiyacı gibi birçok parametreleri kullanmak (bu gibi VC bu çağırır. Hemen terk telif hakkı bildirimi yerinde

0

Bunu denemek olabilir:

[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"userId"] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithFormat:@"%@",_userID] dataUsingEncoding:NSUTF8StringEncoding]]; 
İlgili konular