如何在ios中使用php文件将图像上传到mysql?

时间:2012-06-04 10:40:26

标签: php iphone mysql html

这是我使用php在Mysql上传图像的xcode代码。 NSString * urlString = @“http://www.mysullurpeta.com/iphone/upload.php”;

    NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"world1.jpeg"],90);
    NSLog(@"imageView in data %@/n>>>>%d kb",imageData,imageData.length);


    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];
 NSLog(@"post data is %@", contentType);
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    [request setHTTPBody:imageData];
 NSLog(@"post data is %@",request);

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
        NSLog(@"Data ---- %@", str);

------这是我的php脚本

<?php
echo "file from client: " . $_FILES["filename"]["name"]; 

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 200000))
  {
  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";
  }
?>

我正在尝试将图片移到“上传/”文件中。 它显示错误无效文件。我错了,我不明白。 PLZ ......帮助我...... 谢谢

2 个答案:

答案 0 :(得分:1)

使用此功能,它会在服务器上的文件夹中上传uiimage,而不是在数据库中

+(NSString *)uploadImage:(UIImage *)img :(NSString *)path :(NSString *)name {

NSLog(@"-----------------------image uploadImage uploadImage uploadImage -------------------------");

 /*
 turning the image into a NSData object
 getting the image back out of the UIImageView
 setting the quality to 90
 */
NSData *imageData = UIImageJPEGRepresentation(img, 90);

// setting up the URL to post to

NSString *urlString=WSURL;

// setting up the request object now
NSMutableURLRequest *_request = [[[NSMutableURLRequest alloc] init] autorelease];
[_request setURL:[NSURL URLWithString:urlString]];
[_request setHTTPMethod:@"POST"];

 /*
 add some header info now
 we always need a boundary when we post a file
 also we need to set the content type
 You might want to generate a random boundary.. this is just the same
 as my output from wireshark on a valid html post
 */

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

 /*
 now lets create the body of the post
 */



NSString *name1= [NSString stringWithFormat:@"%@%@",path,name];
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",name1] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
//[body appendData:[NSData i:@"path=%@",path]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[_request setHTTPBody:body];
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:_request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

return(returnString);

}

答案 1 :(得分:0)

使用以下我已经使用此代码成功上传了mysql数据库中的记录,它对我来说很好用

iPhone代码

  NSString *post =[[NSString alloc] initWithFormat:@"ProviderNPI=%@&PatientID=%@&FileURL=%@&FileTYPE=%@&DataSynID=%@&AppointmentListingsID=%@",providerNPI,patientID,FILEURL,FILETYPE,dataSynID,appointmentListingID];



    NSURL *url=[NSURL URLWithString:@"http://www.yourserver.com/Sync.php?"];

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];


    NSError *error;
    NSURLResponse *response;
    NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
    NSLog(@"%@",data);

用于插入数据库的PHP代码

 <?php

 $con = mysql_connect("emriphone.db.6420177.hostedresource.com","emriphone","Light12-");

 if (!$con)


   {

 die('Could not connect: ' . mysql_error());

  }

mysql_select_db("emriphone", $con);

$providernpi=$_POST['ProviderNPI'];
$patientid=$_POST['PatientID'];
$fileurl=$_POST['FileURL'];
$filetype=$_POST['FileTYPE'];
$datasynid=$_POST['DataSynID'];
$appointmentlistingsid=$_POST['AppointmentListingsID'];



  $query=("INSERT INTO AppointmentDataSync   (ProviderNPI,PatientID,FileURL,FileType,DataSyncID,AppointmentListingsID)
VALUES ('$providernpi', '$patientid','$fileurl','$filetype','$datasynid','$appointmentlistingsid')");



mysql_query($query,$con);
printf("Records inserted: %d\n", mysql_affected_rows());


 echo($appointmentlistingsid)


  ?>