php - AFNetworking上传图像间歇性地工作

标签 php objective-c ios cocoa-touch afnetworking

我正在使用AFNetworking将图像以及一些参数上传到PHP脚本(使用CodeIgniter构建),该脚本将接收图像,将文件名和参数放置在数据库中并将图像移至永久位置。

这是Obj-C:

NSURL *url = [NSURL URLWithString:@"http://my_api_endpoint"];
NSData *imageToUpload = UIImageJPEGRepresentation(_mainMedia, .25f);
NSDictionary *params = [[NSDictionary alloc]initWithObjectsAndKeys:
                        _topicText.text,@"Topic",
                        @"1",@"Category",
                        @"1",@"Creator",
                        nil];
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:url];

NSString *timeStamp = [NSString stringWithFormat:@"%0.0f.jpg", [[NSDate date] timeIntervalSince1970]];

NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"apidebate/debates" parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData: imageToUpload name:@"MainMedia" fileName:timeStamp mimeType:@"image/jpeg"];
}];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSString *response = [operation responseString];
    NSLog(@"response: [%@]",response);

    [self dismissViewControllerAnimated:YES completion:nil];
    [self.delegate createTopicViewControllerDidCreate:self];

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    if([operation.response statusCode] == 403){
        NSLog(@"Upload Failed");
        return;
    }
    NSLog(@"error: %@", [operation error]);

    [self dismissViewControllerAnimated:YES completion:nil];
    [self.delegate createTopicViewControllerDidCreate:self];
}];

[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
    float width = totalBytesWritten / totalBytesExpectedToWrite;

}];

[operation start];

这是PHP:
//CONTROLLER FROM API
function debates_post()
{
mail('myemailaddress@gmail.com', 'Test', 'Posted');
$tmp_dir = "images/posted/";

if(isset($_FILES['MainMedia'])){
    $SaniFileName = preg_replace('/[^a-zA-Z0-9-_\.]/','', basename($_FILES['MainMedia']['name']));

    $file = $tmp_dir . $SaniFileName;
    move_uploaded_file($_FILES['MainMedia']['tmp_name'], $file);
}
else
    $SaniFileName = NULL;

$data = array('Topic'=>$this->post('Topic'), 'MainMedia'=>$this->post('MainMedia'), 'Category'=>$this->post('Category'), 'Creator'=>$this->post('Creator'));
$insert = $this->debate->post_debate($this->post('Topic'), $SaniFileName, $this->post('Category'), $this->post('Creator'));
if($insert){
    $message = $this->db->insert_id();
}
else{
    $message = 'Insert failed';
}

$this->response($message, 200);
}

//MODEL
function post_debate($Topic=NULL, $MainMedia='', $Category=NULL, $Creator=NULL){
$MainMedia = ($MainMedia)?$MainMedia:'';
$data = array(
                'Topic' => $Topic,
                'MainMedia' => $MainMedia,
                'Category' => $Category,
                'Creator' => $Creator,
                'Created' => date('Y-m-d h:i:s')
            );
return $this->db->insert('debate_table', $data);
}

我目前的问题是,从iOS上传的文件很少能完成,何时上传则没有模式。我可以仅使用参数就可以添加大或小照片,也可以完全不添加照片,并且20%的时间都可以工作。当它失败时,这是我在X代码中得到的错误消息:
2012-08-26 01:52:10.698 DebateIt[24215:907] error: Error Domain=NSURLErrorDomain 
Code=-1021 "request body stream exhausted" UserInfo=0x1dd7a0d0 
{NSErrorFailingURLStringKey=http://my_api_url, 
NSErrorFailingURLKey=http://my_api_url,
NSLocalizedDescription=request body stream exhausted, 
NSUnderlyingError=0x1e8535a0 "request body stream exhausted"}

这到底是什么?

我有一个基本的HTML表单,可以将相同的图像发布到相同的端点,并且每次都可以处理任何大小的图像。 iOS似乎允许大小不同的图像都很好...但是大小不一,它可能仅在第二次尝试时有效。

有什么想法吗?

最佳答案

我也正在使用AFNetworking上传图像,但是我没有问题,也许是因为我是通过base64编码图像数据的?

NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                               token, @"token",
                               [UIImageJPEGRepresentation(image, 0.8) base64EncodedString],@"photo",
                               nil];

NSMutableURLRequest *request = [self.httpClient requestWithMethod:@"POST"
                                                             path:@"/user/upload/photo.json"
                                                       parameters:params];

关于php - AFNetworking上传图像间歇性地工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12128002/

相关文章:

ios - 尝试像在函数中一样将字典作为参数传递

ios - 为什么 UICollectionView 不滚动其中的 UIButtons?

objective-c - 强制 NStextField 只接受十六进制值

ios - 如何启用 App Thining 功能?

php - 我的 PHP 版本中缺少 XMLReader?

ios - 尝试在 iOS 中验证电子邮件,崩溃不知道为什么?

ios - Xcode 应用程序包 ID 与代码签名 ID 不匹配

Linux下的PHP编程

php - jQuery 将表单选择值添加到远程文件的 $_GET 值

javascript - 我正在尝试使用 javaScript 验证移动设备,但它不起作用