iOSファイルのアップロード
iOSで, ファイルをサーバーに送信する方法です。
NSMutableURLRequest を使って, postします。 multipart属性を使って, postするデータに NSDataを含めれば, ファイルをNSDataにすればファイルの内容を送信できます。
サーバー側で受ける方法ですが,いろいろあると思います。筆者は, Java な人間なので, Servlet + commons fileUpload で受けています。
サンプル
-(void)post:(NSURL *)url file:(NSString *)file
{
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
[urlRequest setHTTPMethod:@"POST"]; // Method type
[urlRequest setTimeoutInterval:120]; // Timeout
[urlRequest setValue:"header" forHTTPHeaderField:"x-head"]; // This is header
[urlRequest setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", kBoundary]
forHTTPHeaderField:@"Content-Type"];
NSMutableData *postData = [[NSMutableData alloc] init];
[postData appendData:[[NSString stringWithFormat:@"--%@\r\n", kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\";filename=\"%@\" \r\n\r\n", @"test"]
dataUsingEncoding:NSUTF8StringEncoding]];
NSData *fileData = [[NSData alloc] initWithContentsOfFile:file];
[postData appendData:fileData];
[postData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[urlRequest setHTTPBody:postData];
NSURLResponse *responce;
NSError *error = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&responce
error:&error];
}
bounddary の文字列 kBoundaryですが, なんでもよかった気がします。
#define kBoundary @"project_boundary"
こんな感じで, プロジェクト名かなんかをいれておけばよいですよ。
解説
通常のリクエストと同じように, NSMutableURLRequestとNSURLConnectionを使っています。この例では, syncですが, asyncでも問題ありません。
リクエストに, multipartに関わる記述を入れてその間に, NSMutableDataをbodyとして入れています。
boundaryの部分を追加していけば, 複数でも, さらに別のデータ(文字列)なども送ることができます。
ん〜, 受ける側も書いておいた方がいいかな。
