开发者

iPhone/Cocoa Upload Image File to PHP on Ubuntu (LAMP)

开发者 https://www.devze.com 2023-04-04 08:00 出处:网络
I\'m trying to upload a small .png file (50x50 pixels) from my iPhone app to my ubuntu server. I\'ve tried several approaches to the problem posted here on StackOverflow and elsewhere on the web but h

I'm trying to upload a small .png file (50x50 pixels) from my iPhone app to my ubuntu server. I've tried several approaches to the problem posted here on StackOverflow and elsewhere on the web but have not had success yet. I've posted my Obj-C code to upload the files and log the server responses, my PHP code on the server, and the response that I am getting. I would really appreciate some help in resolving this - please let me know if you see any issues with my code - Thanks!

Obj-C Code:

// 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(uploadRequest开发者_运维百科Finished:)];
    [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]); 
}

PHP Code on Ubuntu Server:

<?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!"; }
?>

Response from Server:

Upload response  -- Hit Script --
Array
(
)
There was an error uploading the file, please try again!


I think you used the key userfile for uploading the file, and not uploadedfile (use $_FILES['userfile']).

0

精彩评论

暂无评论...
验证码 换一张
取 消