我們開發中常用到圖片上傳,比如頭像上傳之類的,還有類似發佈空間說說時發佈多張圖片等等,我在這裡通過借鑒網路資源,並依賴於七牛雲存儲做了一個圖片上傳的小結。 我首先封裝了一個圖片上傳的工具類,繼承自nsobject,命名為QiniuTool;再多圖上傳時,還需要單張圖片的上傳結果處理,因此,我在這裡有 ...
我們開發中常用到圖片上傳,比如頭像上傳之類的,還有類似發佈空間說說時發佈多張圖片等等,我在這裡通過借鑒網路資源,並依賴於七牛雲存儲做了一個圖片上傳的小結。
我首先封裝了一個圖片上傳的工具類,繼承自nsobject,命名為QiniuTool;再多圖上傳時,還需要單張圖片的上傳結果處理,因此,我在這裡有多創建了一個輔助工具類,命名為QiniuUploadHelper;
工具類類方法:
#import <Foundation/Foundation.h> //上傳 視頻 、n 張圖片 #import <QiniuSDK.h> #import <UIKit/UIKit.h> typedef enum { type_image, type_video }LoadType; @interface QiniuTool : NSObject //獲取七牛上傳token + (void)getQiniuUploadToken:(LoadType)type loadUrl:(NSString *)tokenUrl result:(void(^)(NSDictionary *token))success failure:(void(^)())failure; /** 上傳視頻 @param videoPathUrl 視頻的本地URL路徑 */ //+ (void)uploadVedio:(NSURL *)videoPathUrl success:(void(^)(NSMutableDictionary *result))success failure:(void(^)())failure; /** 上傳單張圖片 @param image 圖片 @param progress 上傳進度 @param success 成功回調 @param failure 失敗回調 */ + (void)uploadImage:(UIImage*)image loadUrl:(NSString *)tokenUrl progress:(QNUpProgressHandler)progress success:(void(^)(NSString*url))success failure:(void(^)())failure; //上傳多張圖片,按隊列依次上傳 + (void)uploadImages:(NSArray*)imageArray loadUrl:(NSString *)tokenUrl progress:(void(^)(CGFloat))progress success:(void(^)(NSArray*urlArray))success failure:(void(^)())failure; @endView Code
實現過程:
#import "QiniuTool.h" #import "QiniuUploadHelper.h" #import "EBirdDefine.h" @implementation QiniuTool //獲取七牛的token // 此處的networkrequest是我最封裝的網路請求工具類 +(void)getQiniuUploadToken:(LoadType)type loadUrl:(NSString *)tokenUrl result:(void (^)(NSDictionary *))success failure:(void (^)())failure { [NetWorkRequest GET_Verify:BASEURL_(tokenUrl) parameters:nil hiddenLoading:NO success:^(NSInteger errorCode, id responseObject, NSString *errorMsg) { if (errorCode == 0 && responseObject) { success(responseObject); } } failure:^(NSError *error) { failure(); }]; } //上傳單張圖片 + (void)uploadImage:(UIImage *)image loadUrl:(NSString *)tokenUrl progress:(QNUpProgressHandler)progress success:(void (^)(NSString *))success failure:(void (^)())failure { [QiniuTool getQiniuUploadToken:type_image loadUrl:tokenUrl result:^(NSDictionary *token) { //此處block中的鍵值應根據後臺設置,取出正確的結果 NSString *tokenStr = [token objectForKey:@"token"]; NSData*data =UIImageJPEGRepresentation(image,0.01); if(!data) { if(failure) { failure(); } return; } NSString*fileName = [token objectForKey:@"key"]; BOOL isHttps = TRUE; QNZone * httpsZone = [[QNAutoZone alloc] initWithHttps:isHttps dns:nil]; QNConfiguration *config = [QNConfiguration build:^(QNConfigurationBuilder *builder) { builder.zone = httpsZone; }]; QNUploadOption *opt = [[QNUploadOption alloc]initWithMime:nil progressHandler:progress params:nil checkCrc:NO cancellationSignal:nil]; QNUploadManager *uploadManager = [QNUploadManager sharedInstanceWithConfiguration:config]; [uploadManager putData:data key:fileName token:tokenStr complete:^(QNResponseInfo*info,NSString*key,NSDictionary*resp) { // 此處的結果應根據後臺設置取出相對應的結果 if(info.statusCode == 200 && [resp count]) { //QiNiuBaseUrl NSString *url; if ([tokenUrl isEqualToString:@"/customers/headImageUploadToken"]) { url = [NSString stringWithFormat:@"%@",resp[@"head_image"]]; }else if ([tokenUrl isEqualToString:@"/repair/imageUploadToken"]) { url = [NSString stringWithFormat:@"%@",resp[@"key"]]; } if(success) { success(url); } }else{ if(failure) { failure(); } } }option:opt]; } failure:^{ failure(); }]; } //上傳多張圖片 + (void)uploadImages:(NSArray *)imageArray loadUrl:(NSString *)tokenUrl progress:(void (^)(CGFloat))progress success:(void (^)(NSArray *urlArray))success failure:(void (^)())failure { NSMutableArray *array = [[NSMutableArray alloc]init]; // __block NSMutableString *string = [NSMutableString string]; // __block CGFloat totalProgress =0.0f; // // __block CGFloat partProgress =1.0f/ [imageArray count]; __block NSUInteger currentIndex =0; QiniuUploadHelper *uploadHelper = [QiniuUploadHelper shareUploadHelper]; __weak typeof(uploadHelper) weakHelper = uploadHelper; uploadHelper.singleFailureBlock= ^() { failure(); return; }; uploadHelper.singleSuccessBlock= ^(NSString*url) { [array addObject:url]; // if (string.length > 0) { // string = [[string stringByAppendingString:@","] mutableCopy]; // string = [[string stringByAppendingString:url] mutableCopy]; // }else // string = [url mutableCopy]; // totalProgress += partProgress; // progress(totalProgress); currentIndex++; if(currentIndex == [imageArray count]) { // [array count] == [imageArray count] success([array mutableCopy]); // [array copy] return; }else{ [QiniuTool uploadImage:imageArray[currentIndex] loadUrl:tokenUrl progress:nil success:weakHelper.singleSuccessBlock failure:weakHelper.singleFailureBlock]; } }; [QiniuTool uploadImage:imageArray[0] loadUrl:tokenUrl progress:nil success:weakHelper.singleSuccessBlock failure:weakHelper.singleFailureBlock]; } /** 已時間給圖片命名 @return pic name */ +(NSString *)getCurrentDateString { NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; NSString *dateString = [formatter stringFromDate:[NSDate date]]; return dateString; } /* +(void)uploadVedio:(NSURL *)videoPathUrl success:(void (^)(NSMutableDictionary *result))success failure:(void (^)())failure { //上傳視頻 [QiniuTool getQiniuUploadToken:type_video result:^(NSDictionary *token) { if ([token count]) { NSData *data = [NSData dataWithContentsOfURL:videoPathUrl]; if (!data) { if (failure) { failure(); } return ; } NSString *tokenStr = [token objectForKey:@"upToken"]; NSString*fileName = [token objectForKey:@"key"]; QNUploadOption *opt = [[QNUploadOption alloc]initWithMime:nil progressHandler:nil params:nil checkCrc:NO cancellationSignal:nil]; QNUploadManager *upManager = [[QNUploadManager alloc] init]; [upManager putData:data key:fileName token:tokenStr complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) { if(info.statusCode == 200 && resp) { if(success) { NSMutableDictionary *resultDic = [NSMutableDictionary dictionary]; [resultDic setObject:[token objectForKey:@"url"] forKey:@"videoUrl"]; UIImage *videoImage = [LMUtil getImage:videoPathUrl]; // 上傳視頻縮略圖 [self uploadImage:videoImage progress:nil success:^(NSString *url) { if (url) { [resultDic setObject:url forKey:@"videoImg"]; success(resultDic); } } failure:^{ failure(); }]; } }else{ if(failure) { failure(); } } } option:opt]; } } failure:^{ failure(); }]; } */ @endView Code
輔助工具類類方法:
#import <Foundation/Foundation.h> @interface QiniuUploadHelper : NSObject @property(nonatomic, copy)void(^singleSuccessBlock)(NSString *); @property (nonatomic, copy)void(^singleFailureBlock)(); +(instancetype)shareUploadHelper; @endView Code
實現:
#import "QiniuUploadHelper.h" @implementation QiniuUploadHelper static id _instance = nil; +(id)allocWithZone:(struct _NSZone *)zone { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [super allocWithZone:zone]; }); return _instance; } +(instancetype)shareUploadHelper { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [[self alloc] init]; }); return _instance; } - (id)copyWithZone:(NSZone*)zone { return _instance; } @endView Code