美文网首页
iOS上实现阿里云OSS断点续传

iOS上实现阿里云OSS断点续传

作者: zbmzly | 来源:发表于2018-06-15 15:46 被阅读0次
    typedef void(^AliyunOSSSuccessBlock) (NSString* fileName);
    typedef void(^AliyunOSSFailBlock)(NSString *errorDescription, NSInteger errorCode);
    typedef void(^AliyunOSSProgressBlock) (int64_t bytesSent, int64_t totalBytes);
    /*!
     OSS断点续传
     @param fileName oss的文件名,最好是随机名字
     @param fileUrl 本地的文件名,断点续传只能用本地文件
     */
    - (void)resumableUploadWithName : (NSString *)fileName
                            fileUrl : (NSURL* ) fileUrl
                            successes:(AliyunOSSSuccessBlock)success
                                 fail:(AliyunOSSFailBlock)fail
                            progress:(AliyunOSSProgressBlock)progress
    {
    
        
        // 获得UploadId进行上传,如果任务失败并且可以续传,利用同一个UploadId可以上传同一文件到同一个OSS上的存储对象
        OSSResumableUploadRequest * resumableUpload = [OSSResumableUploadRequest new];
        resumableUpload.bucketName = OSSBucketKey;
        resumableUpload.objectKey = [NSString stringWithFormat:@"%@%@", OSSObjectKey, fileName];
        resumableUpload.partSize = 1024 * 1024;
        resumableUpload.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
            progress(totalByteSent, totalBytesExpectedToSend);
        };
        NSString *cachesDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
        //设置断点记录文件
        resumableUpload.recordDirectoryPath = cachesDir;
        //设置NO,取消时,不删除断点记录文件,如果不进行设置,默认YES,是会删除断点记录文件,下次再进行上传时会重新上传。
        resumableUpload.deleteUploadIdOnCancelling = NO;
        resumableUpload.uploadingFileURL = fileUrl;
        OSSTask * resumeTask = [client resumableUpload:resumableUpload];
        [resumeTask continueWithBlock:^id(OSSTask *task) {
            if (task.error) {
                NSLog(@"error: %@", task.error);
                fail(task.error.localizedDescription, task.error.code);
                if ([task.error.domain isEqualToString:OSSClientErrorDomain] && task.error.code == OSSClientErrorCodeCannotResumeUpload) {
                    // 该任务无法续传,需要获取新的uploadId重新上传
                } else {
                }
            } else {
                success(fileName);
            }
            return nil;
        }];
    }
    

    相关文章

      网友评论

          本文标题:iOS上实现阿里云OSS断点续传

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