我需要帮助,似乎无法在任何地方找到答案。我有一个应用程序,我想使用PHP将图像存储到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 :(得分: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];
}
享受编码:)
答案 1 :(得分: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);
?>
要发布到MySQL数据库的PHP文件
<?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);
?>