我正在尝试通过邮寄发送图片和一些参数。如果我使用:
NSString * contentType = [NSString stringWithFormat:@ "multipart / form-data, boundary =% @", boundary];
[request setValue:contentType forHTTPHeaderField: @ "Content-Type"];
图像发送正确,但没有字段。
如果我删除图片未发送。
有人可以帮助我吗?
-(int)add:(NSString *)name image:(UIImage *)image email:(NSString *)email dataNasc:(NSString *)dataNasc city:(NSString *)city state:(NSString *)state password:(NSString *)password
{
NSURL *url = [NSURL URLWithString:@"http://mydomains.com/ws/users/add"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSMutableDictionary *_params = [[NSMutableDictionary alloc]init];
[_params setObject:email forKey:@"email"];
[_params setObject:name forKey:@"name"];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"0x0hHai1CanHazB0undar135";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
NSString *BoundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";
NSMutableData *body = [NSMutableData data];
NSData *imageData = UIImageJPEGRepresentation(image, 100);
for (NSString *param in _params) {
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
// add image data
if (imageData) {
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", @"file"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSError *error;
user = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
NSLog(@" %d", [[user objectForKey:@"code"]intValue]);
return [[user objectForKey:@"code"]intValue];
}