我几天来一直试图解决这个问题。我做了很多研究,并尝试了很多其他的东西,但似乎没有任何效果。发布的代码似乎是最接近工作的代码。除图像外,所有数据都填充在数据库中。我想从中获得的是能够发布UIImagePNGRepresentation(图像)返回的确切数据。我假设这是二进制数据,但不是100%。任何帮助,将不胜感激。谢谢!
-(void)sendFormData:(NSArray*)data{
// add boundary
NSString *boundary=@"----Boundary+AaB03x";
// create array of php vars
NSArray *phpVariables=[NSArray arrayWithObjects:@"username",@"picture",@"firstName",@"lastName",@"phone",@"email",@"password",nil];
// create body data
NSMutableData *body=[[NSMutableData alloc] init];
// dictionary of fields
NSMutableDictionary *formFields=[[NSMutableDictionary alloc] init];
// fill dictionary
for(int i=0; i<[data count]-1; i++) [formFields setObject:[data objectAtIndex:i] forKey:[phpVariables objectAtIndex:i]];
NSMutableURLRequest *urlRequest=[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"MY_URL"]];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setValue:[NSString stringWithFormat:@"multipart/form-data, boundary=%@",boundary] forHTTPHeaderField:@"Content-Type"];
NSEnumerator *dictionaryEnumerator=[formFields keyEnumerator];
NSString *currentKey=nil;
while((currentKey=[dictionaryEnumerator nextObject])){
id currentValue=[formFields objectForKey:currentKey];
if([currentValue class]==[UIImage class]){
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"myphoto.png\"\r\n",currentKey] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/x-png\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[@"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:UIImagePNGRepresentation(currentValue)];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
else{
[body appendData:[[NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n",boundary,currentKey,currentValue] dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]];
}
}
[urlRequest setHTTPBody:body];
NSURLResponse *response;
NSError *error;
NSData *serverResponseData=[NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
[body release];
[formFields release];
NSString *serverResponseString=[[NSString alloc] initWithData:serverResponseData
encoding:NSUTF8StringEncoding];
[self performSelectorOnMainThread:@selector(showServerResponseWithString:)
withObject:serverResponseString
waitUntilDone:FALSE];
}
更新
上面的代码工作正常,实际上是PHP的问题。
答案 0 :(得分:1)
我建议使用ASIFormDataRequest来处理这些事情(https://github.com/pokeb/asi-http-request/tree)。它允许避免这样的低级别请求构建,因为它很容易造成一个小错误,使您的请求无效