#import <Foundation/Foundation.h>
@interface UploadImage : NSObject
+ (void)uploadImage:(UIImage *)image fileId:(NSInteger)fileId completion:(void(^)(BOOL isSuccess,id result))completion;
@end
#import "UploadImage.h"
#import "AFNetworking.h"
#import "Photo.h"
@implementation XWUploadImage
+ (void)uploadImage:(UIImage *)image fileId:(NSInteger)fileId completion:(void(^)(BOOL isSuccess,id result))completion
{
NSDictionary * dic = [NSDictionary dictionary];
if (fileId == 0) {
//上传图片
}else {
//修改图片
dic = @{@"fileId":@(fileId)};
}
NSDictionary * params = @{设置其他参数:???,@"dic":dic};
NSMutableString * finalPath = [NSMutableString stringWithFormat:@"%@?",ALUploadImageUrl];
[params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[finalPath appendFormat:@"%@=%@",key,obj];
[finalPath appendFormat:@"&"];
}];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:ALUploadImageUrl]];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSMutableURLRequest *request = [manager.requestSerializer
multipartFormRequestWithMethod:@"POST"
URLString:ALUploadImageUrl
parameters:params
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:@"upload"
fileName:@"upload.png"
mimeType:@"image/png"];
}
error:nil];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
if ([responseObject isKindOfClass:[NSDictionary class]]) {
//自定义一个Photo类
Photo * photo = [[XWPhoto alloc] initWithAttributes:responseObject];
if (completion) {
completion(YES,photo);
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (completion) {
completion(NO,nil);
}
}];
[manager.operationQueue addOperation:operation];
}
@end