我想在mysql数据库中插入带有其他详细信息的图像。我能够保存数据值但是没有插入图像。请检查下面的代码。
(IBAction) addData:(id)sender; {
//Image upload
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 90);
NSString *urlString = @"http://localhost/myservice.php?";
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];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.jpg\"\r\n" 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]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"Image upload string%@",returnString);
//Upload data
NSString *url = [NSString stringWithFormat:[urlString stringByAppendingString:@"userName=%@&age=%@&phone=%@&image=%@"],txtName.text, txtAge.text, txtPhone.text,returnString];
NSData *dataUrl = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
NSString *strResult = [[NSString alloc] initWithData:dataUrl encoding:NSUTF8StringEncoding];
NSLog(@"%@",strResult);
if (![strResult isEqual: @""]) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: @"Record Saved"
message: @"Your Record is saved successfully"
delegate: nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
//Clear fields
txtName.text=@"";
txtAge.text=@"";
txtPhone.text=@"";
imageView.image= nil;
}else {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: @"Record not Saved"
message: @"Your Record does not saved successfully"
delegate: nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
}
答案 0 :(得分:0)
有几个问题:
您的PHP代码不正确。您应该$_FILES
使用userfile
。请参阅Handling File Uploads。
您无法获取二进制数据,只需从中构建SQL语句即可。您可能希望在SQL中使用?
占位符,然后手动将与上载图像关联的blob与mysqli_stmt::bind_param
或类似的东西绑定。
坦率地说,无论如何,这样做是谨慎的,以保护自己免受SQL注入攻击。
对于您的请求未设置的一堆变量,PHP代码引用$_GET
。首先,它应该是$_POST
,而不是$_GET
,其次,如果您的服务器需要这些变量,您应该在请求中设置它们。