用nsurlconnection上传图片出错,求助

直接上代码

 NSURL *url = [NSURL URLWithString:urlStr];
// NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init ]; NSString *boundary = @"---------------------------14737809831466499882746641449"; NSMutableData *postData = [[NSMutableData alloc] init]; [postData appendData:[[NSString stringWithFormat:@" --%@ ",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [postData appendData:[[NSString stringWithFormat:@"Content-Disposition:form-data;name="userfile";filename="%@" ",fileName] dataUsingEncoding:NSUTF8StringEncoding]];
// [postData appendData:[@"Content-Type:application/octet-stream " dataUsingEncoding:NSUTF8StringEncoding]]; [postData appendData:[@"Content-Type:image/png " dataUsingEncoding:NSUTF8StringEncoding]]; [postData appendData:[NSData dataWithData:imgData]]; [postData appendData:[[NSString stringWithFormat:@" --%@-- ",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// NSLog@"data:%@",postData; [request setHTTPBody:postData]; [request addValue:[NSString stringWithFormat:@"%d",int[postData length]] forHTTPHeaderField:@"Content-Length"]; request.URL = url; [request setHTTPMethod:@"POST"]; NSString *contentType = [NSString stringWithFormat:@"multipart/form-data;boundary=%@",boundary]; [request addValue:contentType forHTTPHeaderField:@"Content-Type"]; NSOperationQueue *queue = [[NSOperationQueue alloc]init]; [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^NSURLResponse *response, NSData *data, NSError *connectionError { NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog@"html:%@",html; NSError *error = nil; id jsonObj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error]; if jsonObj != nil { NSLog@"json:%@",jsonObj; } if error != nil { NSLog@"err:%@",error; } }];
结果总是出错,请问我的代码有什么问题吗?

你是个喜欢深挖的程序员,不过这种东西拿着文案一行行对都让人蛋疼。爱莫能助,哈哈。

NSMutableURLRequest 初始化要URL

发表评论

电子邮件地址不会被公开。 必填项已用*标注