5

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

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

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

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

这是我需要使用的网址吗?

4

6 回答 6

5

有很多答案建议 UIImageJPEGRepresentation 或 UIImagePNGRepresentation。但是这些解决方案将转换原始文件,而这个问题实际上是关于按原样保存文件。

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

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

1) 导入照片框架

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) }
                }
            }
        })
    }
}

这将为您提供包含正确名称的文件原样,您甚至可以在准备上传的多部分正文时获取其 UTI 以确定正确的 mimetype(除了通过文件扩展名确定它)。

于 2017-01-11T10:59:39.780 回答
4

有两种方法

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];    

}

注意:ALAssetsLibrary使用ARC时请确定对象的范围。最好将ALAssetsLibrary对象用作单例。

于 2012-08-27T08:44:35.730 回答
3

将照片保存在 Document 目录中并使用该 url 上传。例如

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

将此图片上传为[request setFile:jpgPath forKey:@"image"]

于 2012-08-27T09:29:02.093 回答
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及更高版本。

于 2012-08-27T08:41:50.627 回答
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)
    }
}

第三步: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)")
    }

}
于 2017-09-14T21:38:21.430 回答
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];

  }
于 2012-08-27T09:14:33.807 回答