我有一个例子,我将图像和参数发送到服务器。但是我需要发送NSArray的图像。我怎么能这样做?
NSData *imageToUpload = UIImageJPEGRepresentation(uploadedImgView.image, 1.0);//(uploadedImgView.image);
if (imageToUpload)
{
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:keyParameter, @"keyName", nil];
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://------"]];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"API name as you have" parameters:parameters constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:@"image" fileName:@"temp.jpeg" mimeType:@"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *jsons = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
//NSLog(@"response: %@",jsons);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
if([operation.response statusCode] == 403)
{
//NSLog(@"Upload Failed");
return;
}
//NSLog(@"error: %@", [operation error]);
}];
[operation start];
}
请帮帮我!
答案 0 :(得分:4)
我找到了答案,我将代码更改为:
[formData appendPartWithFileData:data name:@"Photos[1]" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
[formData appendPartWithFileData:data name:@"Photos[2]" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
并且服务器将其理解为数组
答案 1 :(得分:1)
你可以试试这个,
NSURL *url = [NSURL URLWithString:@URL_BASE];
int count = [imageArray count];
for(int i = 0; i < count; ++i)
{
UIImage* image = [imageArray objectAtIndex:i];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat: image.size.width], @"width",
[NSNumber numberWithFloat: image.size.height], @"height",
nil];
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@PATH_ALBUM_IMAGE_UPLOAD parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"file%d", i] fileName:@"avatar.jpg" mimeyTpe:@"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
[progressView setProgress: totalBytesWritten*1.0f / totalBytesExpectedToWrite animated: YES];
NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
if(totalBytesWritten >= totalBytesExpectedToWrite)
{
progressView.hidden = YES;
}
}];
[operation start];
}