美文网首页
iOS 关于OSS上传文件

iOS 关于OSS上传文件

作者: 捉住时间的尾巴 | 来源:发表于2021-04-13 10:17 被阅读0次

    1.安装OSS这些就不需要再说了,其次先让后台配置好一些参数,然后拿到后便可以直接使用了

    目前用到的主要参数有以下三个:
    ServerUrl
    Endpoint
    bucketName

    2.直接在封装好的请求文件 CCNetworkRequstionMD5.m 里面,增加一个方法 (多种文件类型上传,传入你所需要的文件数组即可)

    
    **** 主要代码:*****
    + (void)uploadFileArray:(NSArray *)fileArray success:(void (^)(id res))success{
        
        NSMutableArray * array = [NSMutableArray array];
        id<OSSCredentialProvider> credentialProvider = [[OSSAuthCredentialProvider alloc] initWithAuthServerUrl:OSS_STSTOKEN_URL];
        OSSClientConfiguration *cfg = [[OSSClientConfiguration alloc] init];
        cfg.maxRetryCount = 3;
        cfg.timeoutIntervalForRequest = 15;
        cfg.isHttpdnsEnable = NO;
        cfg.crc64Verifiable = YES;
    
        OSSClient *client = [[OSSClient alloc] initWithEndpoint:OSS_ENDPOINT credentialProvider:credentialProvider clientConfiguration:cfg];
        [OSSManager sharedManager].defaultClient = client;
        
        OSSPutObjectRequest * put = [OSSPutObjectRequest new];
        [fileArray enumerateObjectsUsingBlock:^(CCHomeworkFileModel *fileModel, NSUInteger idx, BOOL * _Nonnull stop) {
            put.bucketName = OSS_BUCKET_PRIVATE;//后台给的currentTimeStr
           
            NSRange startRange = [fileModel.name rangeOfString:@"."];
            NSRange range = NSMakeRange(startRange.location + startRange.length, fileModel.name.length - startRange.location - startRange.length);
            NSString *type = [fileModel.name substringWithRange:range];
            
            // objectKey看看后台需要什么样的格式上传,我们这边的格式是:日期/文件名(13位时间戳) 示例:20210128/1611807485567.jpg
            put.objectKey = [NSString stringWithFormat:@"%@/%lld.%@",[CCNetworkRequstionMD5 getCurrentTime],[DateTranslate getNowTimeStamp],type];
            put.uploadingData = fileModel.data; // 直接上传NSData字节
            put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
                KLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
            };
            
            OSSTask * putTask = [client putObject:put];
            [putTask continueWithBlock:^id(OSSTask *task) {
                if (!task.error) {
                    [array addObject:put.objectKey];//多张图片时这里面存放的图片名字的数组在把这些名字弄成json字符串 给服务器
                    if (fileArray.count > 1) {
                        if (idx == fileArray.count-1) {
                            success(array);
                        }
                    }else{
                        success(array);
                    }
                } else {
                    NSLog(@"upload object failed, error: %@" , task.error);
                }
                return nil;
            }];
            [putTask waitUntilFinished];//这个时sdk给的用于多张图片上传时 加上它时只有第一个走了成功或者失败第二个才会走 。相当于等待串行。
        }];
    }
    
    ****以下不是主要代码,主要记录一下我这边使用的流程,可供参考*****
    /// 获取文件上传成功后调用的
    /// @param objs  oss上传之后返回的ObjectName的数组,由path跟文件名组成,如“20210304/12345678.txt”
    /// @param obj    oss上传之后返回的ObjectName,由path跟文件名组成,如“20210304/12345678.txt”
    /// @param isCompress   是否要进行压缩,某些特定场景需要传,比如添加课件 int
    + (void)getOSSFileUploadSuccessWithArray:(NSArray *)objs WithObj:(NSString *)obj WithIsCompress:(BOOL)isCompress success:(void (^)(id dataArray))success{
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        if(objs.count > 0){
            NSString *str = [objs componentsJoinedByString:@","];
            [dic setObject:str forKey:@"objs"];
        }else{
            [dic setObject:obj forKey:@"obj"];
        }
        // [dic setObject:@"" forKey:@"isCompress"];
        [CCNetworkRequstionMD5 NetRequestGETWithRequestURL:XQ_URLString(URL_File_OSS_Upload) WithParameter:dic isShowHud:NO WithReturnValeuBlock:^(id  _Nonnull returnValue) {
            CCCommonResponse *listModel = returnValue;
            if (listModel.code == HttpCode_normal) {
                NSArray*dataArray = [CCHomeworkFileModel mj_objectArrayWithKeyValuesArray:listModel.data];
                success(dataArray);
            }
        } WithFailureBlock:^(id  _Nonnull errorCode) {
            
        }];
    }
    

    3.以下是在作业上传 CCHomeWorkDetailViewController.m 文件中的使用

    - (void)updateFileRequestWithFilesArray:(NSArray *)filesArray{
        NSMutableArray *nameArray = [NSMutableArray array];
        [filesArray enumerateObjectsUsingBlock:^(CCHomeworkFileModel  *obj, NSUInteger i, BOOL * _Nonnull stop) {
            [nameArray addObject:obj.name];
        }];
        __weak typeof(self) weakSelf = self;
        [CCNetworkRequstionMD5 uploadFileArray:filesArray success:^(id  _Nonnull res) { // 使用OSS先提交 图片、文件 
            [CCNetworkRequstionMD5 getOSSFileUploadSuccessWithArray:res WithObj:@"" WithIsCompress:NO success:^(id  _Nonnull dataArray) { // 获取上传后返回的数据
                [dataArray enumerateObjectsUsingBlock:^(CCHomeworkFileModel  *model, NSUInteger idx, BOOL * _Nonnull stop) {
                       [weakSelf.fileDataArray addObject:@{@"name":nameArray[idx],@"icon":model.icon,@"url":model.url}];
                }];
                [weakSelf getSaveNewNoteRequestWithFilesArray:weakSelf.fileDataArray]; // 提交作业请求
            }];
        }];
    }
    
    - (void)getSaveNewNoteRequestWithFilesArray:(NSArray *)filesArray{
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        if(self.textView.text.length > 0){
            [param setObject:self.textView.text forKey:@"content"];
        }
        [param setObject:[NSString stringWithFormat:@"%d",self.model.id] forKey:@"schoolworkId"];
        if(filesArray.count > 0){
            [param setObject:filesArray forKey:@"files"];
        }else{
            if(self.textView.text.length == 0){
                [HUDUtil ViewWithTitle:@"请先按要求完成作业"];
                return;;
            }
        }
        __weak typeof(self) weakSelf = self;
        [CCNetworkRequstionMD5 NetRequstJsonWithMethod:@"POST" RequestURL:XQ_URLString(URL_Course_Work_Commit) WithParameter:param isShowHud:NO WithReturnValeuBlock:^(id  _Nonnull returnValue) {
            [HUDUtil hideHudAtWindow];
            CCCommonResponse *listModel = returnValue;
            if (listModel.code == HttpCode_normal) {
                // 刷新页面
                [[NSNotificationCenter defaultCenter]postNotificationName:@"ReloadHomeWorkListData" object:@{@"row":[NSString stringWithFormat:@"%zd",self.row],@"page":[NSString stringWithFormat:@"%d",self.page]}];// 刷新作业列表
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
            [HUDUtil ViewWithTitle:listModel.msg];
        } WithFailureBlock:^(id  _Nonnull errorCode) {
            [HUDUtil hideHudAtWindow];
        }];
    }
    

    在了解这方面的知识,找到了这一篇,借鉴了一下
    https://blog.csdn.net/qq_33560608/article/details/88761764

    相关文章

      网友评论

          本文标题:iOS 关于OSS上传文件

          本文链接:https://www.haomeiwen.com/subject/mfuqlltx.html