我想将图像从设备上传到服务器。但是它没有上传!甚至我的返回成功值也显示为空。成功值应该是 1 或 0。我的代码在这里给出。请告诉我我的代码是否有任何错误。预先感谢您的帮助。
-(void)ImageUpload{
NSString *urlString = [NSString stringWithFormat:@"%@upload.php", APIheader];
NSString *postLength = [NSString stringWithFormat:@"%d", [imgDATA length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:urlString]];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:imgDATA];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"return string: %@",returnString);
returnString = [returnString stringByReplacingOccurrencesOfString:@"(" withString:@"["];
returnString = [returnString stringByReplacingOccurrencesOfString:@")" withString:@"]"];
returnString = [returnString stringByReplacingOccurrencesOfString:@";" withString:@""];
SBJsonParser *parser = [[SBJsonParser alloc]init];
NSArray *array = (NSArray *)[parser objectWithString:returnString error:nil];
NSString *status = [NSString stringWithFormat:@"%@",[[array objectAtIndex:0]objectForKey:@"success"]];
if ([status isEqualToString:@"1"]) {
NSLog(@"Image Updated");
}
else{
NSLog(@"status is: %@",status);
}
}
[request release];
}
最佳答案
您可以使用 CoreGraphics
的方法 UIImagePNGRepresentation(UIImage *image)
,它返回 NSData
并保存它。如果您想再次将其转换为 UIImage
,请使用 [UIimage imageWithData:(NSData *data)]
方法创建它。与此相关的一些问题 post image to server in iphone和
How to convert image into binary format in iOS?就像给出相同答案 3 次一样。
- (void)sendImageToServer {
UIImage *yourImage= [UIImage imageNamed:@"image.png"];
NSData *imageData = UIImagePNGRepresentation(yourImage);
NSString *postLength = [NSString stringWithFormat:@"%d", [imageData length]];
// Init the URLRequest
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:[NSString stringWithString:@"http://yoururl.domain"]]];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:imageData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
// response data of the request
}
[request release];
}
关于iphone - 图片没有上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16520222/