简单易懂易使用的上传图片到服务器方法

2016-04-09 咏竹
调用方法
//
//  UpImageByAFNetWorking.h
//  XiaoMei
//
//  Created by 赵诣 on 15/12/2.
//  Copyright © 2015年 apple. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface UpImageByAFNetWorking : NSObject
+ (void)upImageWithUrl:(NSString *)url
               DataDic:(NSDictionary *)dic
              imageArr:(NSMutableArray *)imageArr
           fileNameArr:(NSArray *)fileNameArr
            completion:(void (^)(id result))block;
@end
//
//  UpImageByAFNetWorking.m
//  XiaoMei
//
//  Created by 赵诣 on 15/12/2.
//  Copyright © 2015年 apple. All rights reserved.
//

#import "UpImageByAFNetWorking.h"
#import "Reachability.h"
#import <AFNetworking.h>
@implementation UpImageByAFNetWorking

#pragma mark - 上传多张图片方法
+ (void)upImageWithUrl:(NSString *)url DataDic:(NSDictionary *)dic imageArr:(NSMutableArray *)imageArr fileNameArr:(NSArray *)fileNameArr completion:(void (^)(id))block
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    //    manager.requestSerializer.timeoutInterval = 60;
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/css", @"text/plain", nil]];
    
    [manager POST:url parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        for (int i = 0; i < imageArr.count; i++) {
            NSData *data = UIImageJPEGRepresentation(imageArr[i], 0.5);
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            //设置时间格式
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@.jpeg", str];
            [formData appendPartWithFileData:data name:fileNameArr[i] fileName:fileName mimeType:@"image/jpeg"];
        }
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"图片提交成功");
        if (responseObject) {
            // 通过block回调数据
            block(responseObject);
        } else {
            NSLog(@"返回数据为空, 请检查");
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"图片提交失败~~~~~~~~~~~~~~~~~~%@", error);
        
    }];
    
}

@end