这是我的代码
-(void)uploadNewImageWithURL:(NSString *)strURL andImage:(UIImage *)image andImageNameWithExtension:(NSString *)strImageName{
NSString *path = strURL;
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSDictionary *parameters = @{@"booktitle":@"TestUpload", @"author":@"Harry", @"booktype": @"NF", @"message":@"Test for upload1", @"isbn": @"42000004", @"uploadfile":imageData};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:path parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if(image){
[formData appendPartWithFileData:imageData name:@"image" fileName:strImageName mimeType:@"image/jpeg"];
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"success = %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error = %@", error);
NSLog(@"Response = %@", operation);
}];
}
以下是回复
Response = <AFHTTPRequestOperation: 0x7fe305931e60, state: isFinished, cancelled: NO request: <NSMutableURLRequest: 0x7fe3058a8f20> { URL: http://www.somewhere.com/api/MakeBook/MakeBookNew/ }, response: <NSHTTPURLResponse: 0x7fe305932c70> { URL: www.somewhere.com/api/MakeBook/MakeBookNew/ } { status code: 500, headers {
"Cache-Control" = "no-cache";
"Content-Length" = 1297;
"Content-Type" = "application/json; charset=utf-8";
Date = "Thu, 08 Jan 2015 05:08:51 GMT";
Expires = "-1";
Pragma = "no-cache";
Server = "Microsoft-IIS/7.5";
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";
} }>
答案 0 :(得分:2)
您可以使用以下代码通过AFNetworking上传图片。
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:siteAPIURL]];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
if (headers != nil)
{
NSArray *allHeaders = [headers allKeys];
for (NSString *key in allHeaders)
{
[manager.requestSerializer setValue:[headers objectForKey:key] forHTTPHeaderField:key];
}
}
AFHTTPRequestOperation *op = [manager POST:serviceName parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
//do not put image inside parameters dictionary as I did, but append it!
[formData appendPartWithFileData:imgData name:@"profile_picture" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);
NSLog(@"JSON: %@", responseObject);
if (success != nil)
{
success(operation,responseObject);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure != nil)
{
failure(operation,error);
}
}];
[op start];