【发布时间】:2015-08-17 21:49:24
【问题描述】:
我正在创建一个多部分图像数据上传请求。 我通过 UIImageJPEGRepresentation 从 UIImage 获取 NSData 但是当我尝试将数据转换为字符串时,我得到 nil 值
我已按照此链接将 NSData 转换为 NSString
Convert UTF-8 encoded NSData to NSString
这是我的代码:-
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];
NSMutableString *body = [NSMutableString string];
[body appendFormat:@"--%@\r\n", boundary];
int i =0;
for (UIImage *image in imagesArray) {
NSData *data = UIImageJPEGRepresentation(image, 1.0);
[body appendFormat:@"Content-Disposition:form-data; name=\"userfile[]\"; filename=\"image%d.jpeg\"\r\n",i];
[body appendFormat:@"Content-Type: image/*\r\n\r\n"];
NSString *str = [NSString stringWithUTF8String:[data bytes]]; //this variable should not be nil
[body appendFormat:@"%@",str];
if (error)
{
NSLog(@"%@", error);
}
i++;
}
[body appendFormat:@"\r\n--%@--\r\n", boundary];
NSLog(@"bodyData = %@",body);
我检查了所有变量,它们是正确的,如下
(只有变量“str”不应该为nil。)
最后我得到的正文字符串如下:-
bodyData =
--tqb3fjo6tld9
Content-Disposition:form-data; name="userfile[]"; filename="image0.jpeg"
Content-Type: image/*
(null)
--tqb3fjo6tld9--
【问题讨论】:
-
您不能直接将
NSData转换为NSString,因为数据不代表字符串。您可能需要使用 base64 编码将其转换为字符串。 -
@rmaddy:我点击了这个链接stackoverflow.com/questions/2467844/…
-
该链接与您的需求无关。那是关于包含 UTF-8 编码字符串值的数据。您的数据不是编码的字符串值,而是图像数据。巨大的差异。查看
NSData的文档,了解获取base64 编码的数据字符串的方法。 -
或者,您可以将请求正文创建为可变数据,并将其附加到与您相同的序列转换为数据的字符串
标签: ios objective-c uiimagejpegrepresentation