此函数应该按照HTTP Post将UIImage上传到Web表单。 我在这里和其他帖子中使用了一些帖子的摘录,最后得到了这个。
但它不起作用,就像网址的GET方法一样,至少对我而言。 你也可以对它进行测试,或者帮助我,错误可能在哪里?
我不想使用像ASIHTTPRequest这样的框架。
- (NSString *)postImage:(UIImage *)image toURL:(NSURL *)url {
NSData *imageData = UIImagePNGRepresentation(image);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
NSString *boundary = [NSString stringWithFormat:@"---------------------------%i", (int)[[NSDate date] timeIntervalSinceReferenceDate]*100];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"Photo\"; filename=\"ipodfile.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:@"%d", body.length] forHTTPHeaderField: @"Content-Length"];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
return [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];
}
谢谢, Vincento
答案 0 :(得分:0)
似乎一切都好。 (服务器端都可以)吗? 我在http://code.developwithus.com/iphone/upload-image-and-data-with-iphone-sdk/上放了一个工作示例,你会试试吗?
答案 1 :(得分:0)
您确定要发送的图片不是空吗?如果您尝试发送空的POST数据,它将更改回GET。
答案 2 :(得分:0)
- (void) postCommentsWithImage : message : (NSString*)message imageData : (NSData*)data
{
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:@"POST"];
[theRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
if(data)
{
NSString* pictureDataString = [NSData encode:data];
[dataDictionary setObject:pictureDataString forKey:@"imagebyte"];
}
else
{
[dataDictionary setObject:@"" forKey:@"imagebyte"];
}
NSString *theBodyString = [dataDictionary JSONRepresentation];
[dataDictionary release];
NSData *theBodyData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
[theRequest setHTTPBody:theBodyData];
[theRequest setHTTPBody:theBodyData];
NSLog(@"theRequest=%@", theRequest);
self.connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}