圖片、視頻上傳小記,視頻上傳小記

來源:互聯網
上載者:User

圖片、視頻上傳小記,視頻上傳小記

      我們開發中常用到圖片上傳,比如頭像上傳之類的,還有類似發布空間說說時發布多張圖片等等,我在這裡通過借鑒網路資源,並依賴於七牛雲端儲存做了一個圖片上傳的小結。

      我首先封裝了一個圖片上傳的工具類,繼承自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;@end
View 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();    }];}*/@end
View Code

 

協助工具輔助類類方法:

#import <Foundation/Foundation.h>@interface QiniuUploadHelper : NSObject@property(nonatomic, copy)void(^singleSuccessBlock)(NSString *);@property (nonatomic, copy)void(^singleFailureBlock)();+(instancetype)shareUploadHelper;@end
View Code

實現:

#import "QiniuUploadHelper.h"@implementation QiniuUploadHelperstatic 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;}@end
View Code

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.