Upload an image with AFNetworking 2.0

不打扰是莪最后的温柔 提交于 2019-11-30 03:57:06

For a properly formed "multipart/form-data" body, you need to use use the body construction block while creating the request. Otherwise the upload task is using the raw data as the body. For example, in your AFHTTPSessionManager subclass:

NSString *urlString = [[NSURL URLWithString:kPhotoUploadPath relativeToURL:self.baseURL] absoluteString];
NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:params constructingBodyWithBlock:^(id <AFMultipartFormData> formData) {
    [formData appendPartWithFileData:photo.data name:@"photo" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
}];

NSURLSessionUploadTask *task = [self uploadTaskWithStreamedRequest:request progress:progress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
    if (error) {
        if (failure) failure(error);
    } else {
        if (success) success(responseObject);
    }
}];
[task resume];

Or, if you don't need to track upload progress, you can simply use:

[self POST:kPhotoUploadPath parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:photo.data name:@"photo" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
} success:^(NSURLSessionDataTask *task, id responseObject) {
    if (success) success(responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    if (failure) failure(error);
}];

What Ray Lillywhite describes works perfectly fine (I would've made a comment on his post, but my reputation is too low).

  1. Get the correct version of AFNetworking, containing this fix for updating progress when using multipart requests. At the moment of writing, that version is HEAD.
  2. Create a NSMutableURLRequest with the help of multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:.
    • Build your form data with the help of one of the appendPartWith... methods.
  3. Get a (upload) data task by calling the right uploadTaskWith... method. You NEED to use uploadTaskWithStreamedRequest:progress:completionHandler: if you want to use the NSProgress input parameter.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!