AFHTTPRequestOperationManager post multi-part request not working

亡梦爱人 提交于 2019-11-29 17:09:22

I ended up putting all fields, both text fields and images in the constructingBodyWithBlock. (There's some other stuff in there, like cancelling code and a custom progressbar, but you get the general idea :)

       NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer]
           multipartFormRequestWithMethod:@"POST"
                                URLString:self.destinationUrl
                               parameters:nil
                constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            [formData appendPartWithFormData:[self.userid dataUsingEncoding:NSUTF8StringEncoding] name:@"userid"];
            [formData appendPartWithFormData:[self.phone dataUsingEncoding:NSUTF8StringEncoding] name:@"phone"];

        // Add images as jpeg
        for (UIImage *image in images) {
            NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
            [formData appendPartWithFileData:imageData name:@"myFile" fileName:@"iphoneimage.jpg" mimeType:@"image/jpeg"];
        }

    } 
                                    error:nil];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
        if (!self.httpClientWasCancelled && !self.progressBar.isHidden) {
           [self.progressBar updateCurrentValue:totalBytesWritten/1024 andMax:totalBytesExpectedToWrite/1024];
        }
    }];

    [request setTimeoutInterval:1800];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *responseString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"responseString = %@",responseString);
        [self.progressBar stopAndHide];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Request Error: %@", error);
        if (self.httpClientWasCancelled) {
            self.httpClientWasCancelled = NO;
        } else {
            [self.progressBar stopAndHide];
        }
    }];


    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
     [manager.operationQueue addOperation:operation];

enter code here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!