我有一个图像选择器,可以从内置摄像头中检索图像:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[info objectForKey:UIImagePickerControllerEditedImage];
UIImage *chosenImage = info[UIImagePickerControllerOriginalImage];
self.imageView.image = chosenImage;
NSData *image = UIImagePNGRepresentation(chosenImage);
[self setImageDataToSend:image];
[picker dismissViewControllerAnimated:YES completion:NULL];
}
然后我想用http
上传照片 像这样: NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@"image.png"]);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:[NSURL
URLWithString:@"http://******.co.uk/***/imageupload.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"image/png"
forHTTPHeaderField:@"Content-type"];
[request setValue:[NSString stringWithFormat:@"%lu",
(unsigned long)[imageData length]]
forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:imageData];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
这会选择一个名为" image.png"从应用程序。我希望它从图像选择器中获取NSData *图像
这里也是imageupload.php
:
<?php
$handle = fopen("image.png", "wb"); // write binary
fwrite($handle, $HTTP_RAW_POST_DATA);
fclose($handle);
print "Received image file.";
?>
你知道有更好的方法吗?
答案 0 :(得分:2)
您使用要发送的数据调用方法setImageDataToSend:
,然后在此行中忽略它:
NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@"image.png"]);
您可能想要省略该行并进行更改:
[request setHTTPBody:imageData];
为:
[request setHTTPBody:[self imageDataToSend]];