1
我想從我的iPhone應用上傳一個小的.png文件(50x50像素)到我的Ubuntu服務器。我已經嘗試了幾種方法來解決在StackOverflow和網絡上其他地方發佈的問題,但還沒有成功。我已經發布了我的Obj-C代碼來上傳文件並記錄服務器響應,我的PHP代碼在服務器上,以及我得到的響應。我真的很感謝一些幫助解決這個問題 - 請讓我知道,如果你看到我的代碼的任何問題 - 謝謝!iPhone/Cocoa在Ubuntu(LAMP)上將圖像文件上傳到PHP
的OBJ-C代碼:
// This method uploads the image to the server
-(void)uploadImage{
NSURL *url = [NSURL URLWithString:@"http://mydomain.com/upload.php"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setUseKeychainPersistence:YES];
NSString *fileName = [NSString stringWithFormat:@"%@",self.avatarFileName];
[request addPostValue:fileName forKey:@"name"];
// Upload an image
NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:self.avatarFileName]);
// Make sure it's not null..
NSLog(@"%d",[imageData length]);
// Set the data and filename
[request setData:imageData withFileName:fileName andContentType:@"image/png" forKey:@"userfile"];
[request setDelegate:self];
[request setDidFinishSelector:@selector(uploadRequestFinished:)];
[request setDidFailSelector:@selector(uploadRequestFailed:)];
[request startAsynchronous];
}
- (void)uploadRequestFinished:(ASIHTTPRequest *)request{
NSString *responseString = [request responseString];
NSLog(@"Upload response %@", responseString);
}
- (void)uploadRequestFailed:(ASIHTTPRequest *)request{
NSLog(@" Error - Statistics file upload failed: \"%@\"",[[request error] localizedDescription]);
}
Ubuntu服務器上的PHP代碼:從服務器
<?php
echo ' -- Hit Script --';
print_r($_FILES);
$target_path = "files/";
$target_path = $target_path . basename($_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { echo "The file ". basename($_FILES['uploadedfile']['name']). " has been uploaded"; } else{ echo "There w
as an error uploading the file, please try again!"; }
?>
響應:
Upload response -- Hit Script --
Array
(
)
There was an error uploading the file, please try again!
哇,這是它 - 工作就像一個魅力!非常感謝。 – PhilBot