叹落花 / AFNetworking / iOS关于上传单张及多张图片

分享

   

iOS关于上传单张及多张图片

2019-08-21  叹落花
本章给大家整理一下在iOS中,关于上传单张或多张图片的方法。都是在开发项目中能用到的。我是用的AFNetWorking进行单张和多张图片的上传。话不多说直接上代码。
<<<<<<<<单张图片的上传>>>>>>>>>
========.h文件声明========

+ (void) modifyUserData:(NSDictionary *)dict
              headImage:(UIImage *)img
              completed:(void(^)(NSString * errorCode,NSDictionary *result))completed;

========.m文件声明========
+ (void) modifyUserData:(NSDictionary *)dict
              headImage:(UIImage *)img
              completed:(void(^)(NSString * errorCode,NSDictionary *result))completed{

    AFHTTPRequestOperationManager *manager = [RequestEngine getManager];
    NSData *imageData = UIImageJPEGRepresentation(img, 1);

//////LOGINURL():我这里是一个宏定义,拼接的服务器地址,相信大家都是easy的
    [manager POST:LOGINURL(@"account/updateAccountInfo") parameters:dict constructingBodyWithBlock:^(id formData) {
       
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"filename.jpeg" mimeType:@"image/jpeg"];


       
       
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {

////网络请求成功后的操作,这里的代码就不用贴出来了,每个接口返回参数不同,需要大家自己根据项目实情完成
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
/////这里网络请求出错    
    }];

<<<<<<<<多张图片的上传>>>>>>>>>
======.h文件声明=======
#import
#import "AFNetworking.h"
@interface ZLRequestData : NSObject
@property (nonatomic, strong) AFHTTPRequestOperationManager *operationManager;
+ (ZLRequestData *) sharedOperation;

+(void)startMultiPartUploadTaskWithURL:(NSString *)url
                           imagesArray:(NSArray *)images
                     parameterOfimages:(NSString *)parameter
                        parametersDict:(NSDictionary *)parameters
                      compressionRatio:(float)ratio
                          succeedBlock:(void(^)(id operation, id responseObject))succeedBlock
                           failedBlock:(void(^)(id operation, NSError *error))failedBlock
                   uploadProgressBlock:(void(^)(float uploadPercent,long long totalBytesWritten,long long totalBytesExpectedToWrite))uploadProgressBlock;



======.m文件实现=======

//单例,相信你应该能看懂
+ (ZLRequestData *) sharedOperation{

   static ZLRequestData *zlRequest = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
       
        zlRequest = [[ZLRequestData alloc] init];
       
    });
    zlRequest.operationManager = [AFHTTPRequestOperationManager manager];

    return zlRequest;
}

//////对于参数的传值,在头文件中注释的很清楚
#pragma mark -多张图片上传
+(void)startMultiPartUploadTaskWithURL:(NSString *)url
                           imagesArray:(NSArray *)images
                     parameterOfimages:(NSString *)parameter
                        parametersDict:(NSDictionary *)parameters
                      compressionRatio:(float)ratio
                          succeedBlock:(void (^)(id, id))succeedBlock
                           failedBlock:(void (^)(id, NSError *))failedBlock
                   uploadProgressBlock:(void (^)(float, long long, long long))uploadProgressBlock{
   
    if (images.count == 0) {
        NSLog(@"上传内容没有包含图片");
        return;
    }
    for (int i = 0; i < images.count; i++) {
        if (![images[i] isKindOfClass:[UIImage class]]) {
            NSLog(@"images中第%d个元素不是UIImage对象",i+1);
            return;
        }
    }
   
    AFHTTPRequestOperation *operation = [[[self sharedOperation] operationManager ] POST:url parameters:parameters constructingBodyWithBlock:^(id formData) {
       
        int i = 0;
        //根据当前系统时间生成图片名称
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy年MM月dd日"];
        NSString *dateString = [formatter stringFromDate:date];
       
        for (UIImage *image in images) {
            NSString *fileName = [NSString stringWithFormat:@"%@%d.png",dateString,i];
            NSData *imageData;
            if (ratio > 0.0f && ratio < 1.0f) {
                imageData = UIImageJPEGRepresentation(image, ratio);
            }else{
                imageData = UIImageJPEGRepresentation(image, 1.0f);
            }
           
            [formData appendPartWithFileData:imageData name:parameter fileName:fileName mimeType:@"image/jpg/png/jpeg"];
        }
       
       
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        succeedBlock(operation,responseObject);
       
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        failedBlock(operation,error);
       
    }];
   
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        CGFloat percent = totalBytesWritten * 1.0 / totalBytesExpectedToWrite;
        uploadProgressBlock(percent,totalBytesWritten,totalBytesExpectedToWrite);
    }];
   
}

注:在需要上传多张图片的地方调用+(void)startMultiPartUploadTaskWithURL:(NSString *)url
                           imagesArray:(NSArray *)images
                     parameterOfimages:(NSString *)parameter
                        parametersDict:(NSDictionary *)parameters
                      compressionRatio:(float)ratio
                          succeedBlock:(void(^)(id operation, id responseObject))succeedBlock
                           failedBlock:(void(^)(id operation, NSError *error))failedBlock
                   uploadProgressBlock:(void(^)(float uploadPercent,long long totalBytesWritten,long long totalBytesExpectedToWrite))uploadProgressBlock;这个方法传入对应的值即可。



总结:上传图片一般项目中都会用到,单张与多张照片上传整理好了,可以满足大部分人在开发项目中的需求了。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。如发现有害或侵权内容,请点击这里 或 拨打24小时举报电话:4000070609 与我们联系。

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多
    喜欢该文的人也喜欢 更多

    ×
    ×

    ¥.00

    微信或支付宝扫码支付:

    开通即同意《个图VIP服务协议》

    全部>>