将图像上传到服务器不起作用

时间:2012-02-19 12:55:06

标签: php ios xcode image upload

我正在尝试通过xcode中的php请求将图片上传到我的服务器。我尝试了很多可能性,但到目前为止似乎没有任何效果。我不熟悉php,所以可能存在错误。现在它只是给我错误“不正确的文件类型”,但我肯定使用jpg图像。 (不止一次尝试过)

以下是我在xcode中的内容:

NSData *imageData = UIImageJPEGRepresentation(image.image, 90);
NSString *urlString = @"http://myserver/upload.php";

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:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.jpg\"\r\n"] 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];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

和我的php文件:

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

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']['type'] == "image/jpeg")) && (!($_FILES['userfile']['type']    == "image/png")))           
{
exit("Incorrect file type.  " . $_FILES['userfile']['type'] . " is the file type you     uploaded."); 
}


if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    $postsize = ini_get('post_max_size');   
    $canupload = ini_get('file_uploads');    
    $tempdir = ini_get('upload_tmp_dir');   
    $maxsize = ini_get('upload_max_filesize');
    echo "http://www.mycompanyname.com/myappname/{$file}" . "\r\n" . $_FILES['userfile']['size'] . "\r\n" . $_FILES['userfile']['type'] ;
}

 ?>

2 个答案:

答案 0 :(得分:1)

  

$ _ FILES ['userfile'] ['type']文件的mime类型(如果是浏览器)   提供了这些信息。一个例子是“image / gif”。这个哑剧   但是,在PHP端没有检查类型,因此不需要   它的价值是理所当然的。

http://php.net/manual/en/features.file-upload.post-method.php

如果您想检查mime-type,您应该采用其他方式,例如mime_content_type()

答案 1 :(得分:1)

检查文件类型并检查目录路径$ uploaddir ='/ images /';这是对的吗?这段代码对我来说很好。