iPhone からサーバへhttp通信でファイルアップロードする方法

サーバ側 PHPプログラム
※ 本PHPプログラムは、ファイル名: file_upload.php とする。
※ 本PHPプログラムのディレクトリ配下に”files”ディレクトリを作成しておく。
アップロードされるファイルは、filesディレクトリ配下に作成される。

1
2
3
4
5
6
7
8
9
10
11
12
<?php                                                                                                                         
$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 was an error uploading the file, please try again!"; 
}
?>

クライアント側プログラム
※ ASIHTTPRequest (http://allseeing-i.com/ASIHTTPRequest/)からライブラリ取得する。
iOS用サンプル プログラムの以下の箇所を変更し動作させる。
※ pathForResource メソッドでパスが取得できない場合、プロジェクトの登録情報が不正な場合がある。
問題のリソースファイルを再度、プロジェクトに登録し直せば解決する場合が多い。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@implementation UploadViewController
 
- (IBAction)performLargeUpload:(id)sender
{
    // 以下、ファイルアップロード検証用コード    
    [request cancel];
 
    // 上記のphpプログラムURL
    NSURL *url = [NSURL URLWithString:@"http://xxxxxx/file_upload.php"]; 
    [self setRequest:[ASIFormDataRequest requestWithURL:url]];
 
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
    [request setShouldContinueWhenAppEntersBackground:YES];
#endif
 
    NSBundle *bundle = [NSBundle mainBundle];
    // アップロードテストするファイル
    NSString *pathUploadFile = [bundle pathForResource:@"info" ofType:@"png"];
    NSLog(@"%@", pathUploadFile);
    [request setFile:pathUploadFile forKey:@"uploadedfile"];
 
    [request setUploadProgressDelegate:progressIndicator];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(uploadFinished:)];
    [request setDidFailSelector:@selector(uploadFailed:)];
 
    [request startAsynchronous];
 
    [resultView setText:@"Uploading data..."];
 
// ↑ファイル アップロード検証用コード

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です