直接上代码
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:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithFormat:@"Content-Disposition:form-data;name=\"userfile\";filename=\"%@\"\r\n",fileName]
dataUsingEncoding:NSUTF8StringEncoding]];
// [postData appendData:[@"Content-Type:application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"Content-Type:image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[NSData dataWithData:imgData]];
[postData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",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);
}
}];
结果总是出错,请问我的代码有什么问题吗?