発行したいリクエスト
- POST bodyがバイナリデータで始まる(!= multipart/form-data)
- Content-Typeは
application/octet-stream
POST /storage/files/XXX/upload HTTP/1.1
Host: hoge.example.com
Content-Type: application/octet-stream
Content-Length: 1601207
FileName: test.jpg
(ここにバイナリデータ)
こちらに記載されていることを参考にしました。
実装
+ (void)uploadFile:(NSData *)fileData fileName:(NSString *)fileName callback:(RequestCallback)callback {
NSString *folderId = @"XXX";
NSString *url = [NSString stringWithFormat:@"%@/storage/files/%@/upload", @"https://hoge.example.com", folderId];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
request.HTTPMethod = @"POST";
[request setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];
[request setValue:fileName forHTTPHeaderField:@"FileName"];
[request setHTTPBody:fileData];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"responseObject = %@", responseObject);
callback();
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
callback();
}];
[operation start];
}
Callback周りは、てきとーです。
ちなみにAndroidでは
Retrofitを使えば、簡単です。
@Headers("Content-Type: application/octet-stream")
@POST("/storage/files/{folderId}/upload")
void uploadFile(@Header("FileName") String fileName, @Path("folderId") String folderId, @Body TypedFile file, MyCallback<UploadedFileInfo> callback);
@Body
アノテーションを、TypedFile
につけたら、すんなりバイナリを直接送れました。