【发布时间】:2013-12-20 19:03:48
【问题描述】:
我有以下问题 - 我正在尝试从我的 iOS 应用程序将图像上传到服务器,但我不知道该怎么做。该站点上有一个 HTML 表单,其中包含用于浏览图像的按钮。在我的应用程序中,我从图库中选择了一张照片,然后尝试上传它,但没有任何反应。我使用此代码使事情正常进行,但没有积极的结果:
-(IBAction)postImage:(id)sender
{
NSData *imageData = UIImageJPEGRepresentation(savedImage, 90);
// setting up the URL to post to
NSString *urlString = @"http://pik.bg/news/edit_news/124317";
// setting up the request object now
NSMutableURLRequest *requestUpload = [[NSMutableURLRequest alloc] init];
[requestUpload setURL:[NSURL URLWithString:urlString]];
[requestUpload setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[requestUpload 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 stringWithFormat:@"Content-Disposition: form-data; name=\"Filedata\" filename=\"IMG_0056.JPG\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/jpeg\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
[requestUpload setHTTPBody:body];
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:requestUpload returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog (@"%@", returnString);
}
我做错了什么,但不知道到底是什么。有任何想法吗?哦,如果这很重要的话,HTML 表单有一个名为“submit”的 SUBMIT 按钮。
【问题讨论】: