How to post more parameters with image upload code in iOS?
您好,我正在php服务器上上传图片,并在此代码的帮助下成功上传了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | - (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:@"\ \ --%@\ \ ",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; // [body appendData:[[NSString stringWithFormat:@"userId=%@",_userID] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name="userfile"; filename="image%@.jpg"\ \ ", _userID] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\ \ \ \ "] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[NSData dataWithData:data]]; [body appendData:[[NSString stringWithFormat:@"\ \ --%@--\ \ ",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; } |
现在我想在derver端也发送我的用户ID,我该如何发送我的用户ID?我以这种方式尝试了
1 | [body appendData:[[NSString stringWithFormat:@"userId=%@",_userID] dataUsingEncoding:NSUTF8StringEncoding]]; |
但是徒劳的然后我试图用这种方式发送它
1 2 3 | [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name="userfile"; filename="image%@.jpg"; userId="%@"\ \ ", _userID, _userID] dataUsingEncoding:NSUTF8StringEncoding]]; |
但是又一次徒劳地引导我该怎么做!
如果您尚未考虑使用AFNetworking,则应该这样做。它使处理Web服务变得更加容易。我做了类似我想你想做的事情。我编写了一个自定义类来触发网络请求。在这里,你去:
NetworkClient.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | /* 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | /* 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 |
其中一些特定于我的工作。我所有的Web服务都使用API??Key来增强安全性,并且它们在处理任何请求之前都会进行安全性检查。网络客户端将根据Web服务返回的内容(以JSON形式)返回NSDictionary或NSArray。
要使用图片上传功能,您可以像这样在VC中调用此图片(使用所需的任意数量的参数。:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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 } }]; |
随意删除您不需要的内容。只需保留版权声明即可。
您可以尝试以下操作:
1 2 3 4 5 6 7 8 9 10 11 | [body appendData:[[NSString stringWithFormat:@"\ \ --%@\ \ ",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name="%@"\ \ \ \ ",@"userId"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"%@",_userID] dataUsingEncoding:NSUTF8StringEncoding]]; |