LoginSignup
6
5

More than 5 years have passed since last update.

AFNetworkingでPOST bodyに直接バイナリデータを設定する

Last updated at Posted at 2015-07-22

発行したいリクエスト

  • 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につけたら、すんなりバイナリを直接送れました。

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5