我正在尝试将图片文件上传到http服务器。这是代码片段
NSData *imgData = UIImagePNGRepresentation(img);
NSString *post = [NSString stringWithFormat:@"&UserID=%@&Query=%@&fileContent=", userID, @"putImage"];
NSMutableData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[postData appendBytes:[imgData bytes] length:imgData_len];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSURL *url = [NSURL URLWithString:@"http://ryan.verifyidonline.com/test.php"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:@"POST"];
[theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
[theRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[theRequest setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
此代码仅发送图像文件的前几个字符。我想我必须以某种方式编码文件,但我没有运气尝试NSString编码。
答案 0 :(得分:1)
http://www.cocoadev.com/index.pl?HTTPFileUpload
祝你好运,它给了我一些麻烦,但基于这里的东西(你必须通读底部,固定代码随着时间的推移提交)创建一个干净,可重复使用的方法来做到这一点不应该采取太多很多时间。
答案 1 :(得分:0)
您的代码无法像这样工作。在至少,您需要以某种方式对图像数据进行编码,以便只有ASCII字符(然后不是%,&,=和空格)出现在fileContent的值中。
但是,要正确地执行此操作,您必须创建具有正确内容类型等的多部分MIME正文。我认为Jared的链接中的代码将起作用,但字符集编码中可能存在错误。如果您没有在HTTP中指定字符集,则假定使用ISO-8859-1,但代码似乎在任何地方使用UTF-8而不说字符集是UTF-8。