简体   繁体   中英

Nsmutabledata getting null on append data

I am using below code for uploading image to server.

NSData *imageData = [[[NSData alloc]initWithData:UIImageJPEGRepresentation(m_image.image, 100)]retain];

NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];


//now lets create the body of the post
//set name here

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
if (imageData) {        
    NSLog(@"length %d",[imageData length]);
    [body appendData:[NSData dataWithData:imageData]];
}
NSString *bodystring1 = [[NSString alloc]initWithData:body encoding:NSUTF8StringEncoding];
NSLog(@"body : %@",bodystring1);

Output: length 3826304 body : (null)

As soon as I append image to body its getting null. Anybody any idea. why is this happening?

Try Below code:

-(void) uploadImage
{
NSData *imageData = UIImagePNGRepresentation([dic objectForKey:@"image"]);
// setting up the URL to post to
NSString *urlString =[NSString stringWithFormat:@"%@YOURURL?User_ID=%@",BaseUrl,       [dicobjectForKey:@"User_ID"]];

// setting up the request object now

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
[request setTimeoutInterval:10];

/*
add some header info now
we always need a boundary when we post a file
also we need to set the content type

You might want to generate a random boundary.. this is just the same
as my output from wireshark on a valid html post
*/

NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

/*
now lets create the body of the post
*/

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data;   name=\"profile_photo\"; filename=\"ipodfile.png\"\r\n"]   dataUsingEncoding:NSUTF8StringEncoding]];
// where profile_photo is the key value or parameter value on server. must be confirm

[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];

// now lets make the connection to the web
NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ]; // send data to the web service
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSASCIIStringEncoding];
NSString *trimmedString = [returnString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
NSString *trimmedString1 = [trimmedString stringByReplacingOccurrencesOfString:@"\t" withString:@""];
trimmedString1 = [trimmedString1 stringByReplacingOccurrencesOfString:@"\r" withString:@""];

NSMutableArray *dic0 = [trimmedString1 JSONValue];
NSMutableDictionary *dic1 = [dic0 objectAtIndex:0];
NSLog(@"Profile photo status : %@",[dic1 valueForKey:@"id"]);

}

Let me know for any problem.

这里body包含边界值,内容信息和Image作为NSData。因此将其转换为字符串将仅返回null,因为内部SDK无法识别body中NSData格式的图像。这就是为什么此行返回null的原因。

You can't manipulate image data with string data. As your data will get corrupted by doing so, and that will be unable to form any appropriate result in return. Thus you need to upload strings and images in serpent chunks of data.

I cannot see, that body is nil. You log bodystring1, not body. Probably the image data contains non-valid UTF8-code. -initWithData:encoding: will reject that data and return nil.

It is no good idea, to transform image data into a string directly. Use Base64 encoding or something like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM