如果照片已成功上传

时间:2014-04-23 22:28:48

标签: php ios objective-c http

我希望能够将照片上传到我的网站,一旦完成,就可以找到另一个视图控制器。如果它出现错误xyz:

像:

if (!error) {
   [self performSegueWithIdentifier:@"tocity&country" sender:self];
}
else
{
   NSError *error = [request error];
}

我如何上传照片:

所以目标c代码:

NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@"image.jpg"]);
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
                                    initWithURL:[NSURL
                                                 URLWithString:@"http://******.co.uk/****/imageupload.php"]
                                    cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                    timeoutInterval:20.0];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"image/jpg"
   forHTTPHeaderField:@"Content-type"];
    [request setValue:[NSString stringWithFormat:@"%lu",
                       (unsigned long)[imageData length]]
   forHTTPHeaderField:@"Content-length"];
    [request setHTTPBody:[self imageDataToSend]];

    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    if( theConnection )
    {
        [[NSMutableData data] retain];
    }
    else
    {
        NSLog(@"theConnection is NULL");
    }

    [theConnection release];

imageupload.php

<?php
$handle = fopen("image.jpg", "wb"); // write binary

fwrite($handle, $HTTP_RAW_POST_DATA);

fclose($handle);

print "Received image file.";
?>

我也注意到这样的iphone屏幕顶部没有加载gif,上传图片时怎么样?:

enter image description here


编辑:

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://******.co.uk/****/imageupload.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

//where does the http code come in?

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

2 个答案:

答案 0 :(得分:1)

您的代码存在不同的问题。

  1. 如果您发送POST请求,服务器希望您在上传文件时以标准方式发送使用multipart / form-data编码的正文。对于您正在提出的请求,发送PUT请求更合适。但是,PHP不是使用PUT请求的最佳语言。 (见:http://www.php.net/manual/en/features.file-upload.put-method.php
  2. 要解决格式错误的POST请求问题,同时更好地支持错误等,我建议您使用更高级的库,例如AFNetworking。它内置了上传文件的方法(使用正确编码的multipart / form-data体)和更好的错误处理。
  3. 使用POST请求而不是PUT(在您的代码中,即使您将其声明为POST,您基本上也在执行PUT请求)具有允许您传递更多参数(不使用标头)和更好的支持服务器的优势侧的。
  4. 当您使用正确的POST请求时,您可以只关注服务器端的传统文件上传代码:http://www.php.net/manual/en/features.file-upload.php
  5. 如上所述,活动指示器不会自动出现在iOS上。你必须用

    来调用它
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    

    隐藏它再次调用相同的方法(使用NO参数)。

    PS:不相关,但是......在您的代码中,我看不到文件上传的身份验证。这允许每个人使用任何工具(包括简单的cURL命令)将文件上传到您的服务器。这就是你想要的吗?

答案 1 :(得分:1)

PHP

始终添加检查以确保您确实获得了某些内容,

您可以使用is_uploaded_file试试这样:

<?php 
if(is_uploaded_file($_FILES['image']['tmp_name'])){ 
    $folder = "uploads/"; 
    $file = basename( $_FILES['image']['name']); 
    $full_path = $folder.$file; 
    if(move_uploaded_file($_FILES['image']['tmp_name'], $full_path)) { 
        echo '{"success":true, "msg": "succesful upload, we have an image!"}'; 
    } else { 
        echo '{"success":false, "msg": "upload received! but process failed"}'; 
    } 
}else{ 
    echo '{"success":false, "msg": "upload failure ! Nothing was uploaded"}'; 
} 
?>

目标C

NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@"image.jpg"]);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
                                initWithURL:[NSURL
                    URLWithString:@"http://******.co.uk/****/imageupload.php"]
                                cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                timeoutInterval:20.0];
[request setHTTPMethod:@"POST"];
[request setValue:@"image/jpg" forHTTPHeaderField:@"Content-type"];
[request setValue:[NSString stringWithFormat:@"%lu",
                   (unsigned long)[imageData length]]
forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[self imageDataToSend]];
//Send the Request
NSData* returnData = [NSURLConnection sendSynchronousRequest: request 
                                           returningResponse: nil error: nil];
//serialize to JSON                                          
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];

//parsing JSON
bool success = [result[@"success"] boolValue];
if(success){
    NSLog(@"Success=%@",result[@"msg"]);
}else{
    NSLog(@"Fail=%@"result[@"msg"]);
}