SoFunction
Updated on 2025-04-08

How to upload pictures from albums to servers in iOS

This article shares the specific code for uploading iOS images to the server for your reference. The specific content is as follows

When using the app, it is a very common operation to select pictures from the album as an avatar. First, open the album to select pictures, then save the picture to the document of this application, and finally save the path of the picture in the document to NSUserDefaults and the server.

Select a picture or take a photo from the album

//Select pictures or take photos from the album- (void)btnActionForEditPortrait:(id) sender { 
  UIImagePickerController *picker = [[UIImagePickerController alloc] init]; 
   = self; 
   = UIImagePickerControllerSourceTypePhotoLibrary; 
   = YES; 
  [self presentViewController:picker animated:YES completion:NULL]; 
} 
 
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { 
   
  _avatar = info[UIImagePickerControllerOriginalImage]; 
 
  [self saveImage:_avatar WithName:@"userAvatar"]; 
 
  //After processing, return to the personal information page  [picker dismissViewControllerAnimated:YES completion:NULL]; 
  [_tableView reloadData]; 
} 

Save the picture

//Save the picture- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName 
{ 
  NSData* imageData = UIImagePNGRepresentation(tempImage); 
  NSString* documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
  NSString* totalPath = [documentPath stringByAppendingPathComponent:imageName]; 
   
  //Save to document  [imageData writeToFile:totalPath atomically:NO]; 
   
  //Save to NSUserDefaults  NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; 
  [userDefaults setObject:totalPath forKey:@"avatar"]; 
   
  //Upload the server  [[HSLoginClass new] uploadAvatar:totalPath]; 
} 
 
//Get pictures from document- (UIImage *)getImage:(NSString *)urlStr 
{ 
  return [UIImage imageWithContentsOfFile:urlStr]; 
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.