php - ios 图片上传到服务器不工作

标签 php ios objective-c image-uploading

我正在尝试从 iso 设备上传图像到我的服务器,这是源代码,

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{


    UIImage      *smallImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSString* serverurl = @"http://myserverurl/thumbnailCreator.php";
    NSURL *path = [info valueForKey:UIImagePickerControllerReferenceURL];
    NSString *picPath = [path absoluteString];
    [self uploadImage2:serverurl :smallImage :picPath];

    [picker dismissModalViewControllerAnimated:YES];
}

-(bool)uploadImage2 :(NSString*)php :(UIImage*)image :(NSString*)picPath
{

    int h = image.size.height;
    int w = image.size.width;
    //uploadname =filename;
    NSString* filename = picPath;

    NSError *error;
    NSURLResponse *response;


    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:php]];
    [request setHTTPMethod:@"POST"];

    NSMutableData *body = [NSMutableData data];

    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request addValue:contentType forHTTPHeaderField:@"Content-Type"];
    [request addValue:filename forHTTPHeaderField:@"uploadfile"];


    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploadfile\";filename=\"%@\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[NSData dataWithData:UIImagePNGRepresentation(image)]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];




    // close the form
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    // set request body
    [request setHTTPBody:body];


    // Make synchronous request
    NSData *data1 = [NSURLConnection sendSynchronousRequest:request
                                          returningResponse:&response
                                                      error:&error];
    NSString* outstr = @"NNOK";
    NSString *returnString;
    NSDictionary* json;
    if ([data1 length] > 0 && error == nil)
    {

        returnString = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];

        //drill_debug_info("Response:%s",[returnString UTF8String]);
        NSError* error1;
        json = [NSJSONSerialization
                JSONObjectWithData:data1 //1
                options:kNilOptions
                error:&error1];
        outstr = [json objectForKey:@"Response"]; //2
    }


    if([outstr isEqualToString:@"OK" ])
    {
        return true;
    }
    else
    {
        return false;
    }


}

但是我看不到上传到服务器上的文件并且总是得到 NNOK 结果。上面的代码可能有什么问题。

这是我的服务器 php

<?php
$target_path1 = "images/";
$a=array('Response'=>OK);
$b=array('Response'=>NOK);
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
if(!empty($_FILES)){
//print_r($_FILES);
$target_path1 = $target_path1 . basename( $_FILES['uploaded_file']['name']);
//echo $target_path1;
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1)) {
    echo json_encode($a);
} else{
    // echo "Return Code: " . $_FILES["uploaded_file"]["error"]."size:".$_FILES["uploaded_file"]["size"];
    echo json_encode($b); 
}
}
?>

最佳答案

使用 AFNetworking,像这样尝试:

 #import "AFHTTPRequestOperation.h"
#import "AFHTTPRequestOperationManager.h"

    NSString *stringUrl =@"http://www.myserverurl.com/file/uloaddetails.php?"
    NSString *string =@"http://myimageurkstrn.com/img/myimage.png"       
    NSURL *filePath = [NSURL fileURLWithPath:string];

   NSDictionary *parameters  = [NSDictionary dictionaryWithObjectsAndKeys:userid,@"id",String_FullName,@"fname",String_Email,@"emailid",String_City,@"city",String_Country,@"country",String_City,@"state",String_TextView,@"bio", nil];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    [manager POST:stringUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
     {
         [formData appendPartWithFileURL:filePath name:@"userfile" error:nil];//here userfile is a paramiter for your image 
     }
     success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSLog(@"%@",[responseObject valueForKey:@"Root"]);
         Alert_Success_fail = [[UIAlertView alloc] initWithTitle:@"myappname" message:string delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
         [Alert_Success_fail show];     

     }
     failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         Alert_Success_fail = [[UIAlertView alloc] initWithTitle:@"myappname" message:[error localizedDescription] delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
         [Alert_Success_fail show];

     }];

使用 NSURLConnection:

 -(void)uploadImage
    {       
        NSData *imageData = UIImagePNGRepresentation(yourImage);

        NSString *urlString = [ NSString stringWithFormat:@"http://yourUploadImageURl.php?intid=%@",1];

        NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
        [request setURL:[NSURL URLWithString:urlString]];
        [request setHTTPMethod:@"POST"];

        NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
        [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

        NSMutableData *body = [NSMutableData data];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", 1]] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[NSData dataWithData:imageData]];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [request setHTTPBody:body];

        [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    }

关于php - ios 图片上传到服务器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37339495/

相关文章:

php - 将表迁移到数据库时出错...表已存在

ios - 如何调试 'fatal error: unexpectedly found nil while unwrapping an Optional value'

iphone - 导航栏和 View 之间的分隔符 - iOS 7

javascript - 从选择中选择一个选项,然后使用 Codeigniter 在另一个选择框中显示数据

php - 无法为我的博客设置 CMS 管理员

php - Codeigniter 全局数组声明

ios - swift uicollectionview 单元格和屏幕之间没有空间,只有单元格之间

ios - 如何防止iOS应用程序被挂起

iphone - 如何使用 2 个不同颜色的标签制作 UITableViewCell?

ios - 如何将颜色数组中的文本颜色分配给标签?