AFNetwork 3.0如何上传带有附加数据的文件



如何使用AFNetworking 3.0 uploadTaskWithRequest:fromFile:progress:completionHandler从磁盘实现带有附加信息(在我的情况下为caption&channel_id)的上传文件,以利用新的后台会话上传?

如果它适用于 AFNetworking 和后台文件上传,我愿意接受替代解决方案。

这是我尝试过的服务器响应 400 个错误请求或 500 个内部处理错误(在 cURL 中执行多部分表单发布有效):

@property (nonatomic, strong) AFURLSessionManager *uploadSession;
// Configured uploadSession as backgroundSession configuration with couple of headers
- (void)uploadMediafileFilename:(NSString *)filename
               filenameWithPath:(NSString *)filenameWithPath
                       progress:(void ( ^ ) ( NSProgress *uploadProgress ))progress
                        caption:(NSString *)caption
                        channel:(NSString *)channelId
              completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionBlock {
// ---------
// Create Request Method #1
   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@/", kAPIBaseURL, kAPIMediafilesURL]]];
// Tried dictionary to JSON in body. Also tried a params string version.
   NSDictionary *dict = @{ @"channel_id" : channelId,
                            @"mediafile" : @{ @"filename" : filename, @"caption" : caption } };
   request.HTTPBody = [NSKeyedArchiver archivedDataWithRootObject:dict];
   request.HTTPMethod = @"POST";

// ---- OR ----
// Create Request Method #2
   NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@%@", kAPIBaseURL, kAPIMediafilesURL] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFormData:[caption dataUsingEncoding:NSUTF8StringEncoding] name:@"mediafile[caption]"];
        [formData appendPartWithFormData:[channelId dataUsingEncoding:NSUTF8StringEncoding] name:@"channel_id"];
        [formData appendPartWithFileURL:fileURL name:@"mediafile[filename]" fileName:filename mimeType:@"image/jpeg" error:nil];
    } error:nil];
// ----------
   NSURL *fileURL = [NSURL fileURLWithPath:filenameWithPath];
  [request setValue:[self token] forHTTPHeaderField:kTokenHeaderField];

// Tried using uploadTaskWithRequest - prefer due to its background capabilities. Also tried uploadTaskWithStreamedRequest.
  NSURLSessionUploadTask *uploadTask = [self.uploadSession uploadTaskWithRequest:request fromFile:fileURL progress:progress completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            NSLog(@"%@", [response description]);
        }
        if (completionBlock) {
            completionBlock(response, responseObject, error);
        }
    }];
    [uploadTask resume];
}

我使用以下方法使其工作:

  1. AFURLSessionManager *uploadSession配置为 defaultSessionConfiguration .
  2. 设置NSMutableURLRequest使用上面的方法#2。
  3. 使用AFNetworking的 uploadTaskWithStreamedRequest:progress:completionHandler:

底线:backgroundSessionConfiguration不适用于流式多部分形式,我无法获得要包含在uploadTaskWithRequest:fromFile:中的其他数据。

最新更新