【发布时间】:2015-02-20 02:49:15
【问题描述】:
我想在 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];
}
}
【问题讨论】:
-
你怀疑上面的 Objective-C 代码而不是你的 PHP 代码有什么原因吗?唯一看起来错误的是
HTTPBody开头的前导\r\n。您可以使用Charles 观察此请求,以确保它看起来不错,但这里没有其他明显错误。当然,您不应该使用同步请求,不应该实例化额外的NSData对象,您可能希望避免检索 JPEG 表示等,但这些都不会破坏交易。 -
FWIW,这是我过去使用的代码:stackoverflow.com/a/24252378/1271826
-
Rob..请检查我的 php 代码。
-
我没有看到 PHP 代码(至少现在还没有)。但不要只是用大量代码抛弃我们并期望我们能够诊断它。您确实需要准确地分享您所做的诊断,理想情况下生成一个可重现的问题示例。但是大量带有神秘“它不起作用”的代码并不是可接受的 S.O.问题。