php - 使用 AFNetworking 上传 POST jpeg

标签 php iphone objective-c http afnetworking

我一辈子都弄不明白为什么在我使用 AFNetworking 时这不起作用。它与 ASIHTTP 一起工作。这对我来说都是全新的。但我不明白为什么文件不再从 $_FILES 传输到服务器的 HD。这是 iOS 代码:

- (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');
            }
?>

最佳答案

试试这段代码:

    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]; 

关于php - 使用 AFNetworking 上传 POST jpeg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8557364/

相关文章:

ios - AVPlayer 不播放任何内容

javascript - JQuery onChange 获取之前的值

php - MySQL随机分配第二个端口/PHP

php - 如何在 preg_split() 的结果中包含拆分分隔符?

iphone - 在 cocos2d 中添加 UIViewController

objective-c - 如何获取PubNub单个未读消息的数量?

PHP:准备 PDO 数据库语句的更简洁方法?

iphone - 从 UIPopoverController 拖放到 UIViewController

iphone - Xcode 5命令行:体系结构“arm64”的无效部署目标“3.0.0”

iphone - 在 IMessage 中正确显示视频