1

请帮助我,我正在使用下面的代码来获取文件名。在这里,我NSStringNSDatawhere multipartDatais NSMutableArraywhich contains得到NSData

NSString* postInfo = [[NSString alloc] initWithBytes:[[multipartData objectAtIndex:1] bytes] length:[[multipartData objectAtIndex:1] length] encoding:NSUTF8StringEncoding];

我得到这样的字符串:

Printing description of postInfo:

Content-Disposition: form-data; name="file"; filename="??:??.PNG"

但它应该是这样的:

Printing description of postInfo:

Content-Disposition: form-data; name="file"; filename="华语/華語.PNG"

提前致谢。

4

1 回答 1

0

显然,服务器没有使用 UTF-8 对响应进行编码,但可能是另一种纯中文编码。您需要使用Content-Type标头来检测它是哪种编码,然后NSStringEncoding使用以下代码找到合适的;

// set charset to the MIME charset you get from the server
CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)(charset)));

这是一个详细的答案:

// getting the Content-Type header (e.g. "application/json; charset=utf-8")
NSString* header = [[response allHeaderFields] objectForKey:@"Content-Type"];

// getting the MIME type
NSString* charset = nil;
NSArray* contentTypeParts = [header componentsSeparatedByString:@";"];
NSInteger i = 0;
for (NSString* part in contentTypeParts) {
    // ignoring first loop (e.g. "application/json")
    if (i > 0) {
        NSArray* partComponents = [part componentsSeparatedByString:@"="];
        if ([partComponents count] == 2 && [@"charset" isEqualToString:[[partComponents objectAtIndex:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]]) {
            charset = [[partComponents objectAtIndex:1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            break;
        }
    }
    i++;
}

// converting the MIME type to NSStringEncoding
NSStringEncoding stringEncoding = NSUTF8StringEncoding; // default to UTF8
if (charset) {
    stringEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)(charset)));
}

// finally you can convert your string properly!
NSString* postInfo = [[NSString alloc] initWithBytes:[[multipartData objectAtIndex:1] bytes] length:[[multipartData objectAtIndex:1] length] encoding:stringEncoding];
于 2013-08-26T09:51:48.967 回答