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

时间:2014-10-01 07:18:53

标签: ios objective-c zip base64 url-encoding

我应该将文件转换为 Base64 ,并将该String添加到我附加到URL的JSON中。我所拥有的文件是 .zip 文件和带有 .info 扩展名的文本文件。 .info 文件正在正确上传,但使用 .zip 文件我收到“ 错误填充 ”错误作为回复从服务器。

以下是我的工作;

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

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

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

    NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath:absoluteFilePath];
    [inputStream open];

    uint8_t buffer[1024];

    int len;

    NSMutableString *total = [[NSMutableString alloc] init];

    while ([inputStream hasBytesAvailable]) {
        len = [inputStream read:buffer maxLength:sizeof(buffer)];

        if (len > 0) {
             [total appendString: [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding]];
        }
    }


    NSData *plainData = [total dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64String = [plainData base64EncodedStringWithOptions:0];

// Adding to JSON and upload goes here.
}

我犯了哪些错误?

此外,有没有一种方法可以检查转换后的字符串是否完全符合Base64,然后才附加到JSON并上传到服务器?

由于

2 个答案:

答案 0 :(得分:3)

我发现了错误和答案。我不需要将.zip文件转换为NSInputStream,并且我没有对编码的字符串应用URL安全方法。以下是我处理它的方式。

- (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安全格式化。

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

我也不知道是否有类似的简单方法也可以用iOS。

答案 1 :(得分:0)

试试这个..

+ (NSString *)base64String:(NSString *)str
{
    NSData *theData = [str dataUsingEncoding: NSASCIIStringEncoding];
    const uint8_t* input = (const uint8_t*)[theData bytes];
    NSInteger length = [theData length];

    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    uint8_t* output = (uint8_t*)data.mutableBytes;

    NSInteger i;
    for (i=0; i < length; i += 3) {
        NSInteger value = 0;
        NSInteger j;
        for (j = i; j < (i + 3); j++) {
            value <<= 8;

            if (j < length) {
                value |= (0xFF & input[j]);
            }
        }

        NSInteger theIndex = (i / 3) * 4;
        output[theIndex + 0] =                    table[(value >> 18) & 0x3F];
        output[theIndex + 1] =                    table[(value >> 12) & 0x3F];
        output[theIndex + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
        output[theIndex + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';
    }

    return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}