通过php将图像从UIImagePicker上传到服务器

时间:2014-10-01 06:55:17

标签: ios objective-c uiimage uiimagepickercontroller document

我有一个UIImageView,用于加载用户的个人资料图片。我添加了一些UIImagePicker功能,现在用户可以通过使用相机或从库中添加来更改配置文件图片。这是代码:

- (IBAction)cameraAction:(id)sender {
   UIImagePickerController *picker = [[UIImagePickerController alloc] init];
   picker.delegate = self;
   picker.allowsEditing = YES;
   picker.sourceType = UIImagePickerControllerSourceTypeCamera;

   [self presentViewController:picker animated:YES completion:NULL];
}

- (IBAction)libraryAction:(id)sender {
   UIImagePickerController *picker = [[UIImagePickerController alloc] init];
   picker.delegate = self;
   picker.allowsEditing = YES;
   picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

   [self presentViewController:picker animated:YES completion:NULL];
}

#pragma mark - Image Picker Controller delegate methods

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

   UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
   _profilePhoto.image = chosenImage;
   UIImageWriteToSavedPhotosAlbum(_profilePhoto.image, nil, nil, nil);

   [picker dismissViewControllerAnimated:YES completion:NULL];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

   [picker dismissViewControllerAnimated:YES completion:NULL];

}

现在,我有php文件将当前图像上传到服务器。问题是,php的输入参数是图像文件名。我确实四处寻找并知道要获取图像名称,首先我需要将其保存到应用程序文档目录并使用我想要的名称重命名它。所以任何人都可以告诉我如何将此图像保存到应用程序文档目录,如何获取它以及如何使用我想要的那个重命名它。提前致谢

1 个答案:

答案 0 :(得分:3)

不要以为将文件保存到文档目录会生成新名称。 当我将文件保存到文档时,我会生成唯一的文件名。

我所做的是将一些通用名称传递给Web服务器,例如“Upload.png”。

这是一些伪代码:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
   UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
   [picker dismissViewControllerAnimated:YES completion:NULL];


   ...
   NSData *data = UIImagePNGRepresentation(choosenImage);
   NSString *name = @"Uploaded.png"

   // Upload the nsdata to server
   [[PHPServer instance] uploadProfileImage:data named:name];
}