如何使用 iOS 中的 JSON 数组将图像数量发送到服务器

How to send number of images to server using JSON Array in iOS

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

NSString *imagePostUrl = [NSString stringWithFormat:@"www.abc.com?"];
NSDictionary *parameters = @{@"device_id":string,@"device_phone":[[NSUserDefaults standardUserDefaults] objectForKey:@"SerialNumber"]};

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:imagePostUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:data name:@"uploaded_file" fileName:ext mimeType:@"image/jpeg"];
}];

AFHTTPRequestOperation *op = [manager HTTPRequestOperationWithRequest:request success: ^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"response: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];
op.responseSerializer = [AFHTTPResponseSerializer serializer];
[[NSOperationQueue mainQueue] addOperation:op];

我正在从移动设备的图像路径中的图像中获取图像,我正在将所有带有参数的图像发送到服务器。在这里发送图像是一张一张的带有参数的服务器我可以发送这个吗? 我怎样才能做到这一点?请帮我。提前致谢。

上传图片的正常方式是使用多部分表单编码。阅读此 answer about uploading images using multi-part form data. If you use AFNetworking, it could be done with Multi-Part Request

使用 JSON 你可以使用一个简单的 base64 编码字符串:

UIImage *image  = [[UIImage alloc] init]; //your image here
NSData *data = UIImagePNGRepresentation(image);
NSString *base64string = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

对每张图片执行此操作并发送 JSON 格式的字符串数组。在服务器端,您需要将此字符串解码为图像。但它不是一个好的解决方案。

是的,

我也有同样的建议。

AFNetworking 会像这样为您做到这一点:

-(void)uploadPhoto{
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://server.url"]];

    NSData *imageData = UIImageJPEGRepresentation(self.avatarView.image, 0.5);

    NSDictionary *parameters = @{@"username": self.username, @"password" : self.password};

    AFHTTPRequestOperation *op = [manager POST:@"rest.of.url" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        //do not put image inside parameters dictionary as I did, but append it!
        [formData appendPartWithFileData:imageData name:paramNameForImage fileName:@"photo.jpg" mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@ ***** %@", operation.responseString, error);
    }];
    [op start];
}