简体   繁体   中英

Upload an image to a server folder (objective-c method to php script)

I want to upload an image to a folder on my server. The image is sent to a method in objective-c to a php script. But the upload does not happen! What could be wrong?

Here the obj-C method:

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];

Here the php script:

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

Please help me!

You have to use "POST" method, not "GET".

Here is a nice networking library for iOS: https://github.com/AFNetworking/AFNetworking

There are some code samples on this page, which can help you.

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];

You can read more on GitHub or here: http://afnetworking.com/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM