我想用mysql數據庫中的其他細節插入圖像。我能夠保存數據值,但圖像沒有被插入。請檢查我的代碼如下。如何將圖像插入到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
[email protected]"";
[email protected]"";
[email protected]"";
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](http://charlesproxy.com)觀察這個請求,以確保它看起來不錯,但這裏沒有什麼明顯的錯誤。當然,你不應該使用同步請求,你不應該實例化額外的'NSData'對象,你可能想避免檢索JPEG表示等,但沒有一個是交易斷路器。 – Rob
FWIW,這是我以前使用的代碼:http://stackoverflow.com/a/24252378/1271826 – Rob
Rob。請檢查我的php代碼。 – user3259655