美文网首页
iOS URL安全的Base64编码的文件名和文件大小获取方法

iOS URL安全的Base64编码的文件名和文件大小获取方法

作者: anny_4243 | 来源:发表于2023-07-06 10:55 被阅读0次

    首先在decidePolicyForNavigationResponse方法中打印出navigationResponse.response.suggestedFilename,可以看到文件名为=?UTF8?B?MjAyM+W5tOeOsOaVmeS4reW_g+aakeWBh+WAvOePreihqO+8iA==?= =?UTF8?B?N+aciDXml6UtOeaciDEy5pel77yJLmRvYw==?=

    获取文件名和文件大小的方法如下:

    - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
            //获取文件名称
            NSString *fileName = navigationResponse.response.suggestedFilename;       
              
            if([fileName containString:@"=?UTF8?B?"]){
    
                NSString *encodedString = navigationResponse.response.suggestedFilename;
    
                NSString *decodedString = [self decodeComplexBase64FileName:encodedString];
    
                fileName = decodedString;
        }
    
            //获取文件大小
            NSString *fileSize = [self getFileSize:navigationResponse.response.expectedContentLength];
                                    
            if(self.fileSize.intValue == -1){
    
                self.fileSize = [self getFileSize:[NSData dataWithContentsOfURL:navigationResponse.response.URL].length];
    
            }                           
    }
    
    - (NSString *)decodeComplexBase64FileName:(NSString *)fileName {
        
        //URL安全处理
        NSString *safeBase64String = [fileName stringByReplacingOccurrencesOfString:@"-" withString:@"+"];
        safeBase64String = [safeBase64String stringByReplacingOccurrencesOfString:@"_" withString:@"/"];
        
        NSMutableString *decodedFileName = [NSMutableString string];
        
        NSArray *components = [safeBase64String componentsSeparatedByString:@" "];
        for (NSString *component in components) {
            if ([component hasPrefix:@"=?UTF8?B?"] && [component hasSuffix:@"?="]) {
                NSString *base64String = [component substringWithRange:NSMakeRange(9, component.length - 11)];
                NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
                NSString *decodedComponent = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
                
                if (decodedComponent) {
                    [decodedFileName appendString:decodedComponent];
                }
            } else {
                [decodedFileName appendString:component];
            }
        }
        
        return decodedFileName;
    }
    

    相关文章

      网友评论

          本文标题:iOS URL安全的Base64编码的文件名和文件大小获取方法

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