0

从 iPhone/ipad 上传一些图片到我的网络服务器时遇到问题。确实,我的代码在 MAC 上的模拟器 iPhone 上运行良好,但在真实设备上,它不起作用,图片没有上传到我的服务器上。我不知道问题出在哪里以及为什么它在模拟器上而不是在我的设备上有效。我在 objc 中有这段代码,我调用一个 php 文件将图像保存到服务器。

目标c代码:

NSData *storeData = UIImageJPEGRepresentation(pictureItem, 90); 
NSString *URLString = @"http://url_example/upload.php"; //call upload.php

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

NSString *boundary = @"---------------------------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 stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%d.jpg\"\r\n", idItem] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:storeData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@",returnString);

php文件在这里:

<?php
    $uploaddir = './';      //Uploading to same directory as PHP file
    $file = basename($_FILES['userfile']['name']);
    $uploadFile = $file;
    $newName = $uploadDir . $uploadFile;


    if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
        echo "Temp file uploaded. \r\n";
    } else {
        echo "Temp file not uploaded. \r\n";
    }

    if ($_FILES['userfile']['size']> 10000000) {
        exit("Your file is too large."); 
    }

    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $newName)) {
        $postsize = ini_get('post_max_size');   //Not necessary, I was using these
        $canupload = ini_get('file_uploads');    //server variables to see what was 
        $tempdir = ini_get('upload_tmp_dir');   //going wrong.
        $maxsize = ini_get('upload_max_filesize');
    }
?>

谢谢您的帮助!

4

1 回答 1

0

仔细检查图像文件名的大小写。模拟器通常会原谅文件大小写的差异,但设备通常不会。

例如,如果您的项目中有一个名为 的文件Cat.png,并且在您的代码中将资源引用为cat.png(小写“c”),则它通常可以在模拟器中工作,但不能在设备上工作。

于 2013-03-13T08:52:23.850 回答