用AFNetworking POST jpeg上传

问题描述:

我不能为了我的生活找出为什么当我使用AFNetworking时这不起作用。它与ASIHTTP合作。这对我来说是非常新的。但我不明白为什么这些文件不再从$ _FILES传输到服务器的HD。下面是iOS的代码:用AFNetworking POST jpeg上传

- (IBAction)uploadPressed 
{ 
[self.fileName resignFirstResponder]; 
NSURL *remoteUrl = [NSURL URLWithString:@"http://mysite.com"]; 

NSTimeInterval timeInterval = [NSDate timeIntervalSinceReferenceDate]; 
NSString *photoName=[NSString stringWithFormat:@"%lf-Photo.jpeg",timeInterval]; 

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 

// the path to write file 
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:photoName]; 
NSData * photoImageData = UIImageJPEGRepresentation(self.remoteImage.image, 1.0); 
[photoImageData writeToFile:filePath atomically:YES]; 

NSLog(@"photo written to path: e%@", filePath); 

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:remoteUrl]; 
NSMutableURLRequest *afRequest = [httpClient multipartFormRequestWithMethod:@"POST" 
                     path:@"/photos" 
                   parameters:nil 
                constructingBodyWithBlock:^(id <AFMultipartFormData>formData) 
            { 
             [formData appendPartWithFormData:[self.fileName.text dataUsingEncoding:NSUTF8StringEncoding] 
                    name:@"name"]; 


             [formData appendPartWithFileData:photoImageData 
                    name:self.fileName.text 
                   fileName:filePath 
                   mimeType:@"image/jpeg"]; 
            } 
            ]; 

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:afRequest]; 
[operation setUploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) { 

    NSLog(@"Sent %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite); 

}]; 

    [operation setCompletionBlock:^{ 
    NSLog(@"%@", operation.responseString); //Gives a very scary warning 
}]; 

[operation start];  



} 

我曾经这样做:

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:remoteUrl]; 
[request setPostValue:self.fileName.text forKey:@"name"]; 
[request setFile:filePath forKey:@"filename"]; 
[request setDelegate:self]; 
[request startAsynchronous]; 

这里是我的PHP:

{ 
// these could be stored in a .ini file and loaded 
// via parse_ini_file()... however, this will suffice 
// for an example 
$codes = Array(
    100 => 'Continue', 
    101 => 'Switching Protocols', 
    200 => 'OK', 
    201 => 'Created', 
    202 => 'Accepted', 
    203 => 'Non-Authoritative Information', 
    204 => 'No Content', 
    205 => 'Reset Content', 
    206 => 'Partial Content', 
    300 => 'Multiple Choices', 
    301 => 'Moved Permanently', 
    302 => 'Found', 
    303 => 'See Other', 
    304 => 'Not Modified', 
    305 => 'Use Proxy', 
    306 => '(Unused)', 
    307 => 'Temporary Redirect', 
    400 => 'Bad Request', 
    401 => 'Unauthorized', 
    402 => 'Payment Required', 
    403 => 'Forbidden', 
    404 => 'Not Found', 
    405 => 'Method Not Allowed', 
    406 => 'Not Acceptable', 
    407 => 'Proxy Authentication Required', 
    408 => 'Request Timeout', 
    409 => 'Conflict', 
    410 => 'Gone', 
    411 => 'Length Required', 
    412 => 'Precondition Failed', 
    413 => 'Request Entity Too Large', 
    414 => 'Request-URI Too Long', 
    415 => 'Unsupported Media Type', 
    416 => 'Requested Range Not Satisfiable', 
    417 => 'Expectation Failed', 
    500 => 'Internal Server Error', 
    501 => 'Not Implemented', 
    502 => 'Bad Gateway', 
    503 => 'Service Unavailable', 
    504 => 'Gateway Timeout', 
    505 => 'HTTP Version Not Supported' 
); 

return (isset($codes[$status])) ? $codes[$status] : ''; 
} 

function sendResponse($status = 200, $body = '', $content_type = 'text/html') 
{ 
$status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status); 
header($status_header); 
header('Content-type: ' . $content_type); 
echo $body; 
} 

if (!empty($_FILES) && isset($_POST["name"])) { 
      $name = $_POST["name"]; 
      $tmp_name = $_FILES['filename']['tmp_name']; 
      $uploads_dir = '/var/www/cnet/photos'; 
      move_uploaded_file($tmp_name, "$uploads_dir/$name.jpg"); 
      $result = array("SUCCEEDED"); 
      sendResponse(200, json_encode($result)); 
      } else { 

      sendResponse(400, 'Nope'); 
      } 
?> 
+0

一些评论!($ _ FILES),你应该使用'空',而不是'isset($ _ FILES)'&'$ _FILES ['filename'] ['tmp_name']'将返回上传文件的完整路径,所以如果您在上面添加了'error_reporting(E_ALL)',move_uploaded_file将不起作用你的php文件,然后你会看到错误... – 2011-12-19 05:22:03

+0

谢谢!我继续前进,并从空置变为空置。然后打开error_reporting。但是这是从我的iPhone到服务器。我不知道我应该在哪里看到错误。 而关于move_uploaded_files语法,我直接从PHP手册http://php.net/manual/en/function.move-uploaded-file.php中获取。 – 2011-12-19 06:39:02

+0

我修复了php代码,并使用我的应用程序的旧ASIHTTPFormRequest版本运行它。它仍然是这样的。这个问题肯定在AFNetworking的实施中。 – 2011-12-19 19:13:45

我不是很熟悉的东西ASI与setPostValue:forKey:做,但是您可能会错过name参数与图片上传分开发送。

客户端或服务器会记录什么?进度块日志记录?

其他一些要点:

  • 你可以做[operation start]末;不需要为此创建操作队列。
  • 为了帮助记录日志,请在operation上设置completionBlock,使用响应的NSLog或类似内容。
  • 您可能希望使用类方法创建AFHTTPClient基类以返回单例实例,如AFNetworking示例应用程序中的Gowalla API客户端。该客户端可以管理所有网络请求的单个操作队列。
+0

我将上面的代码调整为最近的代码。验证了PHP的工作原理。我正在尝试完成块,但它不会让我登录operation.responsString。我应该在块中放入什么? – 2011-12-20 20:49:43

+0

Ach!我得到了完成块的工作。它给了我“不要”,这意味着他们至少相互沟通。但我得到了400的回应。所以代码说$ ​​_FILES是空的或$ _POST ['name']没有设置。我还在@“name”appendPartWithFormData中添加了。你可以看到所有最新的两个。 因此,此表单数据尚未正确发送。 – 2011-12-20 21:06:33

+0

当我们更新到2.0后,没有AFHTTPClient并且使用Igor Fedorchuk的代码得到警告,任何新的apis? – jeswang 2014-01-05 02:06:17

我有使用NSMutableURLRequest解决方法:

NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:remoteUrl]; 
[req setHTTPMethod:@"POST"]; 

NSString *contentType = [NSString stringWithFormat:@"multipart/form-data, boundary=%@", boundary]; 
[req setValue:contentType forHTTPHeaderField:@"Content-type"]; 

//adding the body: 
NSMutableData *postBody = [NSMutableData data]; 
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
[postBody appendData:[@"Content-Disposition: form-data; name=\"name\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
[postBody appendData:[name dataUsingEncoding:NSUTF8StringEncoding]]; 

[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
[postBody appendData:[@"Content-Disposition: form-data; name=\"filename\";\r\nfilename=\"china.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
[postBody appendData:[NSData dataWithData:imageData]]; 
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
[req setHTTPBody:postBody]; 

试试这个代码片段:

NSData* sendData = [self.fileName.text dataUsingEncoding:NSUTF8StringEncoding]; 
    NSDictionary *sendDictionary = [NSDictionary dictionaryWithObject:sendData forKey:@"name"]; 
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:remoteUrl]; 
    NSMutableURLRequest *afRequest = [httpClient multipartFormRequestWithMethod:@"POST" 
                      path:@"/photos" 
                    parameters:sendDictionary 
                 constructingBodyWithBlock:^(id <AFMultipartFormData>formData) 
             {          
              [formData appendPartWithFileData:photoImageData 
                     name:self.fileName.text 
                    fileName:filePath 
                    mimeType:@"image/jpeg"]; 
             } 
             ]; 

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:afRequest]; 
    [operation setUploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) { 

     NSLog(@"Sent %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite); 

    }]; 

    [operation setCompletionBlock:^{ 
     NSLog(@"%@", operation.responseString); //Gives a very scary warning 
    }]; 

    [operation start]; 
+0

但是如果有什么方法可以在没有警告的情况下使用它? – jeswang 2014-01-05 02:04:02