使用AFNetworking和PHP从照片库上传选定的图像

我正尝试使用AFNetworking上传一张从照片库中select的图像,但我有点困惑。 一些代码示例正在使用图像数据直接上传,一些正在使用文件path。 我想在这里使用AFNetworking示例代码:

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"]; NSURLRequest *request = [NSURLRequest requestWithURL:URL]; NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"]; NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { if (error) { NSLog(@"Error: %@", error); } else { NSLog(@"Success: %@ %@", response, responseObject); } }]; [uploadTask resume]; 

但我不知道如何才能从图片库中选取图像的path。 谁能告诉我怎样才能得到我从图片库中select的图像path?

编辑1:
好! 我find了以下path解决scheme:

 NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"upload-image.tmp"]; NSData *imageData = UIImageJPEGRepresentation(originalImage, 1.0); [imageData writeToFile:path atomically:YES]; [self uploadMedia:path]; 

现在我仍然感到困惑,因为我已经在我的服务器上创build了上传图片的文件夹。 但AFNetworking如何将这个图像上传到我的文件夹,而无需访问任何service.php页面。 只需http://example.com/upload就足够了? 当我尝试上传时出现以下错误:

 Error: Error Domain=kCFErrorDomainCFNetwork Code=303 "The operation couldn't be completed. (kCFErrorDomainCFNetwork error 303.)" UserInfo=0x1175a970 {NSErrorFailingURLKey=http://www.olcayertas.com/arendi, NSErrorFailingURLStringKey=http://www.olcayertas.com/arendi} 

编辑2:
好。 我设法解决以下代码的错误:

 -(void)uploadMedia:(NSString*)filePath { NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; manager.responseSerializer = [AFHTTPResponseSerializer serializer]; NSURL *requestURL = [NSURL URLWithString:@"http://www.olcayertas.com/fileUpload.php"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL]; [request setHTTPMethod:@"POST"]; NSURL *filePathURL = [NSURL fileURLWithPath:filePath]; NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePathURL progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { if (error) { NSLog(@"Error: %@", error); } else { NSLog(@"Success: %@ %@", response, responseObject); } }]; [uploadTask resume]; } 

我在服务器端使用下面的PHP代码来上传文件:

 <?php header('Content-Type: text/plain; charset=utf-8'); try { // Undefined | Multiple Files | $_FILES Corruption Attack // If this request falls under any of them, treat it invalid. if (!isset($_FILES['upfile']['error']) || is_array($_FILES['upfile']['error'])) { throw new RuntimeException('Invalid parameters.'); error_log("File Upload: Invalid parameters.", 3, "php2.log"); } // Check $_FILES['upfile']['error'] value. switch ($_FILES['upfile']['error']) { case UPLOAD_ERR_OK: break; case UPLOAD_ERR_NO_FILE: throw new RuntimeException('No file sent.'); error_log("File Upload: No file sent.", 3, "php2.log"); case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: throw new RuntimeException('Exceeded filesize limit.'); error_log("File Upload: Exceeded filesize limit.", 3, "php2.log"); default: throw new RuntimeException('Unknown errors.'); error_log("File Upload: Unknown errors.", 3, "php2.log"); } // You should also check filesize here. if ($_FILES['upfile']['size'] > 1000000) { throw new RuntimeException('Exceeded filesize limit.'); error_log("File Upload: Exceeded filesize limit.", 3, "php2.log"); } // DO NOT TRUST $_FILES['upfile']['mime'] VALUE !! // Check MIME Type by yourself. $finfo = new finfo(FILEINFO_MIME_TYPE); if (false === $ext = array_search( $finfo->file($_FILES['upfile']['tmp_name']), array( 'jpg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif', ), true)) { throw new RuntimeException('Invalid file format.'); error_log("File Upload: Invalid file format.", 3, "php2.log"); } // You should name it uniquely. // DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !! // On this example, obtain safe unique name from its binary data. if (!move_uploaded_file($_FILES['upfile']['tmp_name'], sprintf('./uploads/%s.%s', sha1_file($_FILES['upfile']['tmp_name']), $ext))) { throw new RuntimeException('Failed to move uploaded file.'); error_log("File Upload: Failed to move uploaded file.", 3, "php2.log"); } echo 'File is uploaded successfully.'; error_log("File Upload: File is uploaded successfully.", 3, "php2.log"); } catch (RuntimeException $e) { echo $e->getMessage(); error_log("File Upload: " . $e->getMessage(), 3, "php2.log"); } ?> 

编辑3:
现在我已经知道$ _FILES是如何工作的。 如何当我运行我的代码我得到成功的消息,但文件没有上传到服务器。 任何想法可能是错的?

Afnetworking具有通过多部分发布的上传方法。

 NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/v1/api" parameters:parameters constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) { [formData appendPartWithFileData:imageData name:@"filename" fileName:@"file.jpg" mimeType:@"image/jpeg"]; }]; 

imageData是:

 UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage]; NSData *imageData = UIImageJPEGRepresentation(originalImage, 1.0); 

使用下面的代码

 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { [picker dismissViewControllerAnimated:YES completion:nil]; UIImage *image = info[UIImagePickerControllerOriginalImage]; NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init]; [parameters setObject:@"imageUploaing" forKey:@"firstKey"]; NSString *fileName = [NSString stringWithFormat:@"%ld%c%c.jpg", (long)[[NSDate date] timeIntervalSince1970], arc4random_uniform(26) + 'a', arc4random_uniform(26) + 'a']; AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; NSData *data = UIImageJPEGRepresentation(image, 0.5); [manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { [formData appendPartWithFileData:data name:@"image" fileName:fileName mimeType:@"image/jpeg"]; } success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"Success: %@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }]; } 

虽然还有其他方法可以上传图片,但是如果您想要使用您描述的方法,那么在select图片之后,您可以像这样获取其URL:

 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL]; } 

这是假设你使用UIImagePickerController来select一个图像。