使用AFNetworking和PHP从照片库上载选定图像
我正试图上传一张图片,它是用AFNetworking从照片库中选择的,但我有点困惑。有些代码示例直接使用图像数据进行上传,有些使用文件路径。我想在这里使用AFNetworking示例代码:使用AFNetworking和PHP从照片库上载选定图像,php,ios,file-upload,afnetworking-2,Php,Ios,File Upload,Afnetworking 2,我正试图上传一张图片,它是用AFNetworking从照片库中选择的,但我有点困惑。有些代码示例直接使用图像数据进行上传,有些使用文件路径。我想在这里使用AFNetworking示例代码: NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; AFURLSessionManager *manager = [[AFURLSessionManager
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];
但我不知道如何才能得到我从照片库中选择的图像路径。
有人能告诉我怎样才能得到我从照片库中选择的图像路径吗
编辑1:好啊我找到了路径的以下解决方案:
NSString *path = [NSTemporaryDirectory()
stringByAppendingPathComponent:@"upload-image.tmp"];
NSData *imageData = UIImageJPEGRepresentation(originalImage, 1.0);
[imageData writeToFile:path atomically:YES];
[self uploadMedia:path];
现在我仍然感到困惑,因为我已经在我的服务器上为上传的图像创建了一个文件夹。但是AFNetworking将如何在不访问任何service.php页面的情况下将此图像上载到我的文件夹。就够了吗?当我尝试上传时,出现以下错误: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:现在我已经了解了$\u文件的工作原理。然而,当我运行代码时,我会收到一条成功消息,但文件并没有上传到服务器。知道有什么问题吗?虽然还有其他上传图像的方法,但是如果您想使用您描述的方法,那么在选择图像后,您可以像下面这样获得其URL:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
}
这是假设您使用
UIImagePickerController
选择图像。虽然还有其他上传图像的方法,但如果您想使用您描述的方法,那么在选择图像后,您可以像下面这样获得其URL:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
}
这是假设您使用
UIImagePickerController
选择图像。Afnetworking有一种通过多部分post上传的方法
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"];
}];
Afnetworking有一种通过多部分post上传的方法
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"];
}];
使用以下代码
- (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);
}];
}
-(void)imagePickerController:(UIImagePickerController*)选取器未使用信息完成PickingMediaWithInfo:(NSDictionary*)信息{
[picker DismissionViewControllerInitiated:是完成:无];
UIImage*image=info[UIImagePickerController原始图像];
NSMutableDictionary*参数=[[NSMutableDictionary alloc]init];
[parameters setObject:@“ImageUploing”forKey:@“firstKey”];
NSString*文件名=[NSString stringWithFormat:@“%ld%c%c.jpg”,(长)[[NSDate date]时间间隔1970],arc4random_uniform(26)+“a”,arc4random_uniform(26)+“a”);
AFHTTPRequestOperationManager*manager=[AFHTTPRequestOperationManager];
NSData*data=UIImageJPEG表示法(图像,0.5);
[经理职务:@”http://example.com/resources.json“参数:参数constructingBodyWithBlock:^(id formData){
[formData appendPartWithFileData:数据名称:@“图像”文件名:文件名mimeType:@“图像/jpeg”];
}成功:^(AFHTTPRequestOperation*操作,id响应对象){
NSLog(@“成功:%@”,响应对象);
}失败:^(AFHTTPRequestOperation*操作,NSError*错误){
NSLog(@“错误:%@”,错误);
}];
}
使用以下代码
- (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);
}];
}
-(void)imagePickerController:(UIImagePickerController*)选取器未使用信息完成PickingMediaWithInfo:(NSDictionary*)信息{
[picker DismissionViewControllerInitiated:是完成:无];
UIImage*image=info[UIImagePickerController原始图像];
NSMutableDictionary*参数=[[NSMutableDictionary alloc]init];
[parameters setObject:@“ImageUploing”forKey:@“firstKey”];
NSString*文件名=[NSString stringWithFormat:@“%ld%c%c.jpg”,(长)[[NSDate date]时间间隔1970],arc4random_uniform(26)+“a”,arc4random_uniform(26)+“a”);
AFHTTPRequestOperationManager*manager=[AFHTTPRequestOperationManager];
NSData*data=UIImageJPEG表示法(图像,0.5);
[经理职务:@”http://example.com/resources.json“参数:参数constructingBodyWithBlock:^(id formData){
[formData appendPartWithFileData:数据名称:@“图像”文件名:文件名mimeType:@“图像/jpeg”];
}成功:^(AFHTTPRequestOperation*操作,id响应对象){
NSLog(@“成功:%@”,响应对象);
}失败:^(AFHTTPRequestOperation*操作,NSError*错误){
NSLog(@“错误:%@”,错误);
}];
}
我仍然需要一个service.php页面才能获得此文件wright?我仍然需要一个service.php页面才能获得此文件wright?您曾经使用过此功能吗?我也有同样的问题。为什么很难找到答案?我原以为成千上万的人会想把图片上传到他们的网站上。而不是使用像parse这样的网站。是的,我有,我会尽快用工作代码更新问题。但我对目前的解决方案并不满意。它看起来很脆弱,也不安全。目前我还没有达到我最初的目标,所以我正在做一项深入的工作。哦,做得好!我可以看一下吗?如果你懒得给我看的话,请不要担心。不过,请你完成后通知我好吗?当它把我逼疯的时候?你能给我指出目前的任何链接或任何东西吗?你有没有用过这个?我也有同样的问题。为什么很难找到答案?我原以为成千上万的人会想把图片上传到他们的网站上。而不是使用像parse这样的网站。是的,我有,我会尽快用工作代码更新问题。但我对目前的解决方案并不满意。它看起来很脆弱,也不安全。目前我还没有达到我最初的目标,所以我正在做一项深入的工作。哦,做得好!我可以看一下吗?如果你懒得给我看的话,请不要担心。不过,请你完成后通知我好吗?当它把我逼疯的时候?你能给我指出目前的任何链接或任何东西吗?。