UploadImage上传图片

#import 

@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 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

你可能感兴趣的:(UploadImage上传图片)