2013-07-25 90 views
0

我想將圖像上傳到服務器上的文件夾。該圖像被髮送到一個方法在objective-c到一個PHP腳本。但上傳不會發生!什麼可能是錯的?將圖像上傳到服務器文件夾(objective-c方法爲php腳本)

這裏的OBJ-C方法:

NSURLConnection *getConnection; 
NSData *imgData = UIImageJPEGRepresentation(self.imageView.image, 0.7); 
NSMutableString *strURL = [NSMutableString stringWithFormat:@"http://.../uploadPhoto.php?ID=2&ph=%@",imgData]; 

[strURL setString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:strURL]]; 
[request setHTTPMethod:@"GET"]; 
getConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; 

這裏的PHP腳本:

$ID = $_GET[ID]; 
    $ph = $_FILES['ph']; 
    $filename =$ID; 
    move_uploaded_file($ph['tmp_name'], $_SERVER['DOCUMENT_ROOT']."https://stackoverflow.com/users/$ID/$filename"); 

請幫幫我!

+0

試POST方法,[要求setHTTPMethod:@ 「POST」],林不知道 – Nightmare

回答

0

您必須使用「POST」方法,而不是「GET」。

這裏是iOS的一個很好的網絡庫: https://github.com/AFNetworking/AFNetworking

有此頁面上的一些代碼示例,它可以幫助你。

NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"]; 
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; 
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5); 
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST"  path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) { 
    [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"]; 
}]; 

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { 
    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite); 
}]; 
[httpClient enqueueHTTPRequestOperation:operation]; 

你可以閱讀更多在GitHub上或在這裏:http://afnetworking.com/

+0

,並在PHP腳本我應該怎麼改? – Joker

相關問題