Upload an image with AFNetworking 2.0

后端 未结 2 2038
暖寄归人
暖寄归人 2020-12-28 21:18

I can\'t understand why this is so hard. All the tutorials and articles online seem to be talking about the 1.0 api, which is pretty useless.

I\'ve tried a few diffe

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-28 21:54

    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  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 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);
    }];
    

提交回复
热议问题