gpt4 book ai didi

php - 使用AFNetworking和PHP从照片库上传所选图像

转载 作者:行者123 更新时间:2023-12-01 17:08:26 25 4
gpt4 key购买 nike

我正在尝试使用AFNetworking上传从照片库中选择的图像,但我有点困惑。一些代码示例直接使用图像数据进行上传,而另一些则使用文件路径。我想在这里使用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];

但是我不知道如何获得从照片库中选择的图像路径。
谁能告诉我如何从照片库中获取选择的图像的路径?

编辑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页面的情况下将此图像上传到我的文件夹。仅 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);

关于php - 使用AFNetworking和PHP从照片库上传所选图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21400842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com