Reputation: 865
I try to send image as byte[] to server. When I sent it from POST-MAN, like html will send files, it works.
But when I try to send from Objective C code, it sents different array of bytes:
+ (void)uploadPhoto:(UIImage*)photo withCompletionBlock:(responceBlock)block
{
AFHTTPRequestOperationManager* manager = [[AFHTTPRequestOperationManager alloc] init];
NSData* imageData = UIImageJPEGRepresentation(photo, 6);
[manager.requestSerializer setValue:[UserDefaultsHelper getToken] forHTTPHeaderField:@"X-AUTH-TOKEN"];
AFHTTPRequestOperation* op = [manager POST:@"http://localhost:8080/image/save"
parameters:@{}
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:@"ParamFiles" fileName:@"photo2131231.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];
}
Answer: Sorry for stupid question. Problem, that on server I handle just binary image. Objective C code send me multipart files, so it contains binary image with filename, mimetype and other fields. I converted everything to bytes and tried to save this like image. Of course server can't do that.
Upvotes: 2
Views: 1390
Reputation: 1169
Try this out
+ (void)uploadPhoto:(UIImage*)photo withCompletionBlock:(responceBlock)block
{
AFHTTPRequestOperationManager* manager = [[AFHTTPRequestOperationManager alloc] init];
NSData* imageData = UIImageJPEGRepresentation(photo, 6);
[manager.requestSerializer setValue:[UserDefaultsHelper getToken] forHTTPHeaderField:@"X-AUTH-TOKEN"];
NSMutableURLRequest * request = [manager.requestSerializer
multipartFormRequestWithMethod:@"POST"
URLString:@"http://localhost:8080/image/save"
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
UIImage *image = [page.imageVersionObject imageForVersion:page.imageVersionObject.selectedVersion];
if (image) {
[formData appendPartWithFileData:UIImageJPEGRepresentation(image, (CGFloat)0.85)
name:@"file"
fileName:@"fileName.jpg"
mimeType:@"image/jpeg"];
}
}
error:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//SUCCESS HERE!!!
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//FAILURE HERE
}];
[manager.operationQueue addOperation:operation];
}
Do not forget to use your filename and name.... I have used mine for testing
Upvotes: 2