用户使用UIImagePickerController
从iPhone库中选择图片后,我想使用ASIHTTPRequest
库将其上传到我的服务器。
我知道使用ASIHTTPRequest
我可以使用文件的URl上传文件,但如何获取图片网址?
我知道我可以获得图像UIImagePickerControllerReferenceURL
,如下所示:
"assets-library://asset/asset.JPG?id=F2829B2E-6C6B-4569-932E-7DB03FBF7763&ext=JPG"
这是我需要使用的网址吗?
答案 0 :(得分:4)
有两种方式
<强> 1 强>
您可以使用 imagePickerController 委托
上传图片- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
//Upload your image
}
<强> 2 强>
您可以使用此
保存已挑选的图片网址并稍后上传- (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
对象的范围。
答案 1 :(得分:3)
将照片保存在文档目录中并使用该网址上传。例如
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.jpg"];
[UIImageJPEGRepresentation(img, 1.0) writeToFile:jpgPath atomically:YES];
将此图片上传为[request setFile:jpgPath forKey:@"image"]
;
答案 2 :(得分:2)
有许多答案表明UIImageJPEGRepresentation或UIImagePNGRepresentation。但是这些解决方案将转换原始文件,而这个问题实际上是关于按原样保存文件。
看起来直接从资产库上传文件是不可能的。但是可以使用PHImageManager访问它以获取实际的图像数据。以下是:
Swift 3 (Xcode 8,仅适用于iOS 8.0及更高版本)
1)导入Photos框架
import Photos
2)在imagePickerController(_:didFinishPickingMediaWithInfo :)中获取资产URL
3)使用fetchAssets(withALAssetURLs:options:)
获取资产4)使用requestImageData获取实际图像数据(for:options:resultHandler :)。在此方法的结果处理程序中,您将获得数据以及文件的URL(可以在模拟器上访问URL,但遗憾的是在设备上无法访问 - 在我的测试中,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) }
}
}
})
}
}
这将为您提供AS IS文件,包括其正确的名称,您甚至可以让UTI确定正确的mimetype(除了通过文件扩展名确定),同时准备上传多部分正文。
答案 3 :(得分:1)
获取图像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 及更高版本。
答案 4 :(得分:1)
我找到的最简单方法是
第1步:获取DocumentsDirectory的路径
func fileInDocumentsDirectory(filename: String) -> String {
let documentsFolderPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as NSString
return documentsFolderPath.appendingPathComponent(filename)
}
步骤2:使用tempFileName保存路径
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:在需要时获取图像
获得像这样的参考
let localfilepath = self.fileInDocumentsDirectory(filename:&#34; temp_dummy_image.png&#34;)
步骤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)")
}
}
答案 5 :(得分:0)
您可以通过创建表单来上传图片,请尝试以下代码
-(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];
}