问题
I am creating a multipart image data upload request. i am getting NSData from UIImage by UIImageJPEGRepresentation but when i try to convert the data into string i am getting nil value
i have followed this link to convert NSData to NSString
Convert UTF-8 encoded NSData to NSString
here is my code :-
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);
I have checked all the variables and they are correct, and are as follows
(only variable "str" should not be nil.)
and finally i am getting the body string as follows :-
bodyData =
--tqb3fjo6tld9
Content-Disposition:form-data; name="userfile[]"; filename="image0.jpeg"
Content-Type: image/*
(null)
--tqb3fjo6tld9--
回答1:
Your mistake is thinking that the JPEG representation of an image is a UTF-8-encoded string. It's not. It's arbitrary binary data. UTF-8 strings aren't arbitrary sequences of bytes; there are rules about what bytes can follow other bytes.
You want to encode your JPEG data as a string suitable for use in an HTTP form submission. One way is to use base64 encoding, like this:
[body appendString:@"Content-Type: image/*\r\n"];
[body appendString:@"Content-Transfer-Encoding: base64\r\n\r\n"];
[body appendString:[data base64EncodedStringWithOptions: NSDataBase64Encoding76CharacterLineLength]];
On the other hand, you could use the binary
encoding and include the raw JPEG data directly. In that case, you would need to change the type of body
to NSMutableData
and build it up with different methods, as you cannot append arbitrary binary data to an NSMutableString
.
UPDATE
In Swift, with an NSMutableString
:
let data = UIImageJPEGRepresentation(image, 0.5)!
let body = NSMutableString()
body.append("Content-Type: image/*\r\n")
body.append("Content-Transfer-Encoding: base64\r\n\r\n")
body.append(data.base64EncodedString(options: .lineLength76Characters))
In Swift, with a String
:
let data = UIImageJPEGRepresentation(image, 0.5)!
var body = ""
body += "Content-Type: image/*\r\n"
body += "Content-Transfer-Encoding: base64\r\n\r\n"
body += data.base64EncodedString(options: .lineLength76Characters)
来源:https://stackoverflow.com/questions/30624266/cant-convert-nsdata-to-nsstring-when-using-uiimagejpegrepresentation