美文网首页
调用系统文件夹上传文件

调用系统文件夹上传文件

作者: 叶神游戏 | 来源:发表于2020-12-16 15:15 被阅读0次

    调用系统文件夹主要用到了UIDocumentPicker,上传文件使用AFNetWorking

    1.首先接受<UIDocumentPickerDelegate>

    2.在点击事件中加入

    //文件类型      
     NSArray *documentTypes = @[@"public.content", @"public.text", @"public.source-code ", @"public.image", @"public.audiovisual-content", @"com.adobe.pdf", @"com.apple.keynote.key", @"com.microsoft.word.doc", @"com.microsoft.excel.xls", @"com.microsoft.powerpoint.ppt"];
            
     UIDocumentPickerViewController *documentPickerViewController = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:documentTypes                                                     inMode:UIDocumentPickerModeOpen];
     documentPickerViewController.delegate = self;
      [[self viewController] presentViewController:documentPickerViewController animated:YES completion:nil];
    

    3.在UIDocumentPickerDelegate中处理回调事件

    -(void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
    {
        NSArray *array = [[url absoluteString] componentsSeparatedByString:@"/"];
        NSString *fileName = [array lastObject];
        fileName = [fileName stringByRemovingPercentEncoding];
    
        NSArray *fileArray=[fileName componentsSeparatedByString:@"."];
        
        //判断URL是否能找到,如果直接用url很可能找不到对应的文件
        BOOL canAccessingResource = [url startAccessingSecurityScopedResource];
        if(canAccessingResource) {
            NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
            NSError *error;
            [fileCoordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
                NSData *fileData = [NSData dataWithContentsOfURL:newURL];
               
                //上传文件
               NSString *urlString2=@“”;
    
               [manager POST:urlString2 parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    
                //这里面可以追加参数或者上传的文件
                [formData appendPartWithFileData:fileData name:@"file" fileName:fileArray.firstObject mimeType:[NSString stringWithFormat:@"file/%@",fileArray.lastObject]];
    
                 } progress:^(NSProgress * _Nonnull uploadProgress) {
    
                  } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                               
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    
                 NSLog(@"%@",error);
                }];
            }];
            if (error) {
                // error handing
            }
        } else {
            // startAccessingSecurityScopedResource fail
        }
    //    [url stopAccessingSecurityScopedResource];
    
    }

    相关文章

      网友评论

          本文标题:调用系统文件夹上传文件

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