如何上传从UIImagePickerController获取的图像

用户使用UIImagePickerController从iPhone库中select图像后,我想使用ASIHTTPRequest库将其上传到我的服务器。

我知道,使用ASIHTTPRequest我可以用文件的URl上传文件,但是如何获取图像的URL?

我知道我可以得到图像UIImagePickerControllerReferenceURL ,看起来像这样:

 "assets-library://asset/asset.JPG?id=F2829B2E-6C6B-4569-932E-7DB03FBF7763&ext=JPG" 

这是我需要使用的URL吗?

将照片保存到文档目录中,然后使用该url进行上传。例如,

 NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.jpg"]; [UIImageJPEGRepresentation(img, 1.0) writeToFile:jpgPath atomically:YES]; 

上传这张图片为[request setFile:jpgPath forKey:@"image"] ;

有两种方法

1:

您可以使用imagePickerController委托上传图像

 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{ UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage]; //Upload your image } 

2:

您可以保存选取的图片url,然后使用它进行上传

 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{ NSString *imageUrl = [NSString stringWithFormat:@"%@",[info valueForKey:UIImagePickerControllerReferenceURL]]; //Save the imageUrl } -(void)UploadTheImage:(NSString *)imageUrl{ NSURL *url = [[NSURL alloc] initWithString:imageUrl]; typedef void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *asset); typedef void (^ALAssetsLibraryAccessFailureBlock)(NSError *error); ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset){ ALAssetRepresentation *rep = [myasset defaultRepresentation]; CGImageRef iref = [rep fullResolutionImage]; UIImage *myImage = nil; if (ref) { myImage = [UIImage imageWithCGImage:iref scale:[rep scale] orientation:(UIImageOrientation)[rep orientation]]; //upload the image } }; ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror){ }; ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease]; [assetslibrary assetForURL:url resultBlock:result block failureBlock:failureblock]; 

}

注意:请确保在使用ARC.Better将ALAssetsLibrary对象作为单例使用时,确保ALAssetsLibrary对象的作用域。

获取图像UIImagePickerControllerReferenceUR。 这个示例代码如下

 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL]; ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset) { ALAssetRepresentation *representation = [myasset defaultRepresentation]; NSString *fileName = [representation filename]; NSLog(@"fileName : %@",fileName); CGImageRef ref = [representation fullResolutionImage]; ALAssetOrientation orientation = [[myasset valueForProperty:@"ALAssetPropertyOrientation"] intValue]; UIImage *image = [UIImage imageWithCGImage:ref scale:1.0 orientation:(UIImageOrientation)orientation]; }; ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease]; [assetslibrary assetForURL:imageURL resultBlock:resultblock failureBlock:nil]; } 

注意:它仅适用于iOS 5及更高版本。

有很多答案,build议UIImageJPEGRepresentation或UIImagePNGRepresentation。 但这些解决scheme将转换原来的文件,而这个问题实际上是关于保存文件的原因。

它看起来像直接从资产库上传文件是不可能的。 但是可以使用PHImageManager来获取实际的图像数据。 就是这样:

Swift 3 (Xcode 8,仅适用于iOS 8.0及更高版本)

1)导入照片框架

 import Photos 

2)在imagePickerController(_:didFinishPickingMediaWithInfo :)获取资产URL

3)使用fetchAssets提取资产(使用ALAssetURLs:options 🙂

4)使用requestImageData获取实际的图像数据(用于:options:resultHandler :)。 在这个方法的结果处理程序中,您将拥有数据以及该文件的URL(该URL可以在Simulator上访问,但不幸的是无法在设备上访问 – 在我的testing中,startAccessingSecurityScopedResource()总是返回false)。 但是这个URL对于找出文件名仍然很有用。

示例代码:

 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { dismiss(animated: true, completion: nil) if let assetURL = info[UIImagePickerControllerReferenceURL] as? URL, let asset = PHAsset.fetchAssets(withALAssetURLs: [assetURL], options: nil).firstObject, let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first, let targetURL = Foundation.URL(string: "file://\(documentsPath)") { PHImageManager.default().requestImageData(for: asset, options: nil, resultHandler: { (data, UTI, _, info) in if let imageURL = info?["PHImageFileURLKey"] as? URL, imageData = data { do { try data.write(to: targetURL.appendingPathComponent(imageURL.lastPathComponent), options: .atomic) self.proceedWithUploadFromPath(targetPath: targetURL.appendingPathComponent(imageURL.lastPathComponent)) } catch { print(error) } } } }) } } 

这将给你的文件,包括其正确的名称,你甚至可以得到它的UTI,以确定正确的mimetype(除了通过文件扩展名确定),同时准备上传多部分机构。

我发现的最简单的方法是

第1步:获取DocumentsDirectory的path

 func fileInDocumentsDirectory(filename: String) -> String { let documentsFolderPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as NSString return documentsFolderPath.appendingPathComponent(filename) } 

步骤2:使用tempFileName保存path

  func saveImage(image: UIImage, path: String ) { let pngImageData = UIImagePNGRepresentation(image) do { try pngImageData?.write(to: URL(fileURLWithPath: path), options: .atomic) } catch { print(error) } } 

第3步:在imagePickerController函数中使用

 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){ if var image = info[UIImagePickerControllerOriginalImage] as? UIImage {// image asset self.saveImage(image: image, path: fileInDocumentsDirectory(filename: "temp_dummy_image.png")) } 

步骤4:要求时获取图像

得到这样的参考

让localfilepath = self.fileInDocumentsDirectory(文件名:“temp_dummy_image.png”)

第5步:使用图像后,垃圾的临时图像

 func removeTempDummyImagefileInDocumentsDirectory(filename: String) { let fileManager = FileManager.default let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! as NSURL let documentsPath = documentsUrl.path do { if let documentPath = documentsPath { let fileNames = try fileManager.contentsOfDirectory(atPath: "\(documentPath)") print("all files in cache: \(fileNames)") for fileName in fileNames { if (fileName.hasSuffix(".png")) { let filePathName = "\(documentPath)/\(fileName)" try fileManager.removeItem(atPath: filePathName) } } let files = try fileManager.contentsOfDirectory(atPath: "\(documentPath)") print("all files in cache after deleting images: \(files)") } } catch { print("Could not clear temp folder: \(error)") } } 

你可以通过创build表单上传图片尝试下面的代码

 -(void)UploadImage{ NSString *urlString = @"yourUrl"; NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:[NSURL URLWithString:urlString]]; [request setHTTPMethod:@"POST"]; NSMutableData *body = [NSMutableData data]; NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"]; NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; [request addValue:contentType forHTTPHeaderField:@"Content-Type"]; // file NSData *imageData = UIImageJPEGRepresentation([self scaleAndRotateImage:[selectedImageObj]],90); [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; // [body appendData:[[NSString stringWithString:@"Content-Disposition: attachment; name=\"user_photo\"; filename=\"photoes.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"%@.jpg\"\r\n",@"ImageNmae"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[NSData dataWithData:imageData]]; [body appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; // close form [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; // set request body [request setHTTPBody:body]; //return and test NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; }