2014-06-14 32 views
-1

我需要帮助,似乎无法在任何地方找到答案。我有一个应用程序,我想使用PHP将图像存储到MySQL。这里是我使用的代码,我不明白我在做什么错...任何帮助将不胜感激。使用PHP从iOS上传图像到MySQL

NSString *urlString = @"http://homeWeb.local/postPicSK.php?"; 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
[request setURL:[NSURL URLWithString:urlString]]; 
[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"]; 

// picture 
UIImage *image = imageView.image; 
CGFloat compression = 0.5f; 

//UIImage *smallSizeImage = [self scaleImage:image toSize:CGSizeMake(140.0, 80.0)]; 
NSData *imageData = UIImageJPEGRepresentation(image, compression); 

// date and time 
NSDate* date = [NSDate date]; 
NSDateFormatter* formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
NSString* dateAndTime = [formatter stringFromDate:date]; 

//[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"test\"; filename=\"%@ %@.jpg\"\r\n", [self userNameFetch], dateAndTime] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[@"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]]; 

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

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

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

NSLog(@"%@", returnString); 

我的PHP文件:

<?php 
$hostusername = "root"; 
$hostpassword = "root"; 
$hostname = "127.0.0.1"; 

$courtname = $_POST['name']; 
echo "Court Name:".$courtname."<br>"; 

$image1 = file_get_contents($_FILES['image']['name']); 
echo $image1; 

//connection to the database 
$dbhandle = mysql_connect($hostname, $hostusername, $hostpassword) 
or die("Unable to connect to MySQL"); 

//select a database to work with 
$selected = mysql_select_db("scoreKeeper",$dbhandle) 
    or die("Could not select userName"); 

$query = mysql_query("INSERT INTO teamData (courtName, liveGameFeedImages) 
      VALUES ('$courtname',$image1')"); 

if($query) 
{ 
    echo"Successful"; 
} else { 
    echo"Error"; 
} 

//close the connection 
mysql_close($dbhandle); 
?> 
+0

你有什么问题? – Jens

+0

我无法得到它发布到数据库或得到任何回声 – user961632

+1

通常不是一个好的做法,在数据库中存储图像。 – Prashant

回答

0

它的更好,如果你可以使用AFnetworking的上传图片,

其相当快速,简单

下面我更新的代码,请请看:

NSData *imageDataNew; 
    CGFloat compression = 1.0f; 
    CGFloat maxCompression = 0.1f; 
    int maxFileSize = 250 * 1024; 
    UIImage *image = [UIImage imageWithContentsOfFile:THIS.fullPathToFile]; 
    NSData *imageData = UIImageJPEGRepresentation(image, compression); 
    while ([imageData length] > maxFileSize && compression > maxCompression) 
    { 
     compression -= 0.1; 
     imageDataNew = UIImageJPEGRepresentation(image, compression); 
    } 
    int random = arc4random() % 9999999; 
    NSString *photoName=[NSString stringWithFormat:@"%d-Photo.png",random]; 


    // NSLog(@"new pwd is =%@",passwordTxtF.text); 
    AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://yoururlname/project/"]]; 
    [client defaultValueForHeader:@"Accept"]; 
    NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"HMU/broadcast.php?" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) 
            { 
             [formData appendPartWithFileData:imageData name:@"file" fileName:photoName mimeType:@"image/png"]; 
            }]; 
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
    [operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) 
    { 
     NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite); 

    }]; 
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) 
    { 

     NSData *data = (NSData *)responseObject; 
     NSError *error; 
     NSArray *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 
     NSLog(@"dict is %@", dict); 
     NSString *message1=[dict valueForKey:@"message"]; 
     NSLog(@"message=%@",message1); 
     NSString *status=[dict valueForKey:@"status"]; 
     if ([status isEqualToString:@"1"]) 
     { 
       UIAlertView *alrt=[[UIAlertView alloc]initWithTitle:@"HMU APP!" message:message1 delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 
      [alrt show]; 
     } 
     else if ([status isEqualToString:@"0"]) 
     { 
       [hud hide:YES]; 
      UIAlertView *alrt=[[UIAlertView alloc]initWithTitle:@"HMU APP!" message:message1 delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 
      [alrt show]; 
      alrt.tag=2; 

     } 
    } 
      failure:^(AFHTTPRequestOperation *operation, NSError *error) 
    { 

    }]; 
    [operation start]; 
} 

欣赏编码:)

+0

感谢您的发布,但我使用了AFNetworking 2.0解决方案,而不是您发布的1.x解决方案。我的解决方案贴在下面,谢谢你的帮助! – user961632

0

下面是我想出的解决方案,似乎工作。我希望它能帮助有同样问题的其他人。

.m文件

- (IBAction)post:(id)sender 
{ 

    // filter the comment field 
    filteredPostText = [commentTextView.text iod_filteredString]; 

    // compress image 
    CGFloat compression = 1.0f; 
    UIImage *image = imageView.image; 
    NSData *imageData = UIImageJPEGRepresentation(image, compression); 

    // create file name 
    int random = arc4random() % 9999999; 
    NSString *photoName=[NSString stringWithFormat:@"%d-Photo.jpg",random]; 


    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc]  initWithBaseURL:[NSURL URLWithString:@"http://homeWeb.local"]]; 
    manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 
    NSDictionary *parameters = @{@"courtName": courtName, @"fileName": photoName}; 
    AFHTTPRequestOperation *op = [manager POST:@"postPicSK.php?" parameters:parameters  constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
     [formData appendPartWithFileData:imageData name:@"image" fileName:photoName  mimeType:@"image/jpeg"]; 
    } success:^(AFHTTPRequestOperation *operation, id responseObject) { 
     NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject); 
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     NSLog(@"Error: %@ ***** %@", operation.responseString, error); 
    }]; 
    [op start]; 
} 

PHP文件发布到一个文件夹

<?php 
$hostusername = "root"; 
$hostpassword = "root"; 
$hostname = "127.0.0.1"; 

$courtname = $_POST['courtName']; 
echo "Court Name:".$courtname."<br>"; 

$filename = $_POST['fileName']; 
$target_path = "uploads/"; 

$target_path = $target_path . basename($_FILES['image']['name']); 

if(move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) 
{ 
    echo "The file ". basename($_FILES['image']['name'])." has been uploaded"; 
} else { 
    echo "There was an error uploading the file, please try again!"; 
} 

//close the connection 
mysql_close($dbhandle); 
?> 

PHP文件张贴到MySQL数据库

<?php 
$hostusername = "root"; 
$hostpassword = "root"; 
$hostname = "127.0.0.1"; 

$courtname = $_POST['courtName']; 
echo "Court Name:".$courtname."<br>"; 

$image1 = basename($_FILES['image']['tmp_name']); 
echo "Image:".$image1."<br>"; 

$tmp_img = $_FILES['image']['tmp_name']; 

//connection to the database 
$dbhandle = mysql_connect($hostname, $hostusername, $hostpassword) 
or die("Unable to connect to MySQL"); 
//echo "Connected to MySQL<br>"; 

//select a database to work with 
$selected = mysql_select_db("scoreKeeper",$dbhandle) 
    or die("Could not select userName"); 

$query = mysql_query("INSERT INTO teamData (courtName, liveGameFeedImages) 
      VALUES ('$courtname','$tmp_img')"); 

if($query) 
{ 
    echo"Successful"; 
} else { 
    echo"Error"; 
} 

//close the connection 
mysql_close($dbhandle); 
?>