来自iphone app的文件上传服务器

时间:2012-03-14 08:32:42

标签: iphone objective-c

  

可能重复:
  Uploading image to server in iphone application

我正在从iphone应用程序上传文件,但它没有上传我正在使用PHP脚本它工作正常当我用HTML运行此脚本但不使用xcode probelm是该应用程序不是从iphone上传服务器中的图像。

PHP代码

<?php
   if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/jpg"))
    && ($_FILES["file"]["size"] < 20000000000))
   {
  if ($_FILES["file"]["error"] > 0)
   {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
   else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
   echo "Type: " . $_FILES["file"]["type"] . "<br />";
   echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
   echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

     if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
       }
      else
       {
       move_uploaded_file($_FILES["file"]["tmp_name"],
       "upload/" . $_FILES["file"]["name"]);
       echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
     }
  }
    else
       {
     echo "Invalid file";
     }
?>

Xcode iphone code

- (BOOL)uploadImage:(NSData *)imageData filename:(NSString *)filename{

    NSString *urlString = @"http://www.celeritas-solutions.com/emrapp/Image.php";

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL  URLWithString:urlString] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];
    [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 stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
   [body appendData: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] autorelease];    
    return ([returnString isEqualToString:@"OK"]);

}

[self uploadImage:UIImageJPEGRepresentation(imageView.image, 1.0) filename:@"pig.jpg"];

0 个答案:

没有答案