大雑把なやり方。
PHP スクリプト。
<?php
$target_path = "./";
$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 was an error uploading the file, please try again!";
}
?>
IOS コード
- (void)upload:(UIImage *)image {
NSData *imageData = UIImageJPEGRepresentation(image, 80);
NSString *urlString = @"http://www.upload.com/upload.php"; // URL of upload script.
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=\"uploadedfile\"; filename=\"test.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(@"returnString: %@", returnString);
}
使用する変数名が同じであることを確認してください。ここでは、php と ioscode の両方に「uploadedfile」を使用します。
php
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path))
iOS
[body appendData:[@"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// 現在はhttps://github.com/samvermette/SVHTTPRequestを使用していますが、
そのライブラリをコードにインポートすると、アップロードはこれと同じくらい簡単になります
[SVHTTPRequest POST:@"http://www.upload.com/upload.php"
parameters:[NSDictionary dictionaryWithObjectsAndKeys:imageData, @"uploadedfile", nil]
progress:^(float progress) {
progressLabel.text = [NSString stringWithFormat:@"Uploading (%.0f%%)", progress*100];
}
completion:^(id response, NSHTTPURLResponse *urlResponse, NSError *error) {
progressLabel.text = @"Upload complete";
}];