且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 iOS 中将文件转换为 Base64 URL 安全编码格式

更新时间:2023-02-23 19:21:56

我已经找到了错误和答案.我不需要将 .zip 文件转换为 NSInputStream 并且我没有将 URL 安全方法应用于编码字符串.以下是我解决它的方法.

I have found the mistakes as well as the answer. I do not need to convert the .zip file in to NSInputStream and I haven't applied URL safe methods to the encoded string. Following is the way I have tackled it.

- (void)uploadingData: (NSString *)fileName {

    NSArray *directoryPathsArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [directoryPathsArray objectAtIndex:0];

    NSString *absoluteFilePath = [NSString stringWithFormat:@"%@/%@/%@", documentsDirectory, baseDirName, fileName];

    NSData *zipFileData = [NSData dataWithContentsOfFile:absoluteFilePath];

    NSString *base64String = [zipFileData base64EncodedStringWithOptions:0];

    base64String = [base64String stringByReplacingOccurrencesOfString:@"/"
                                                            withString:@"_"];

    base64String = [base64String stringByReplacingOccurrencesOfString:@"+"
                                                           withString:@"-"];

// Adding to JSON and upload goes here.
}

Android 中,有一种方法可以使用单个函数进行 Base64 编码和 URL 安全格式设置.

In Android there is a way to do both Base64 encoding and URL safe formatting with a single function.

byte[] bytes = Files.toByteArray(new File(sFileName));
byte[] encoded = Base64.encodeBase64URLSafe(bytes);

我不知道在 iOS 上是否也有类似的简单方法.

I have no idea whether there is a similar kind of easy way of doing it with iOS too.